变量不设置在案例之间? [英] Variables not setting between cases?

查看:93
本文介绍了变量不设置在案例之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Cells.Count > 1 Then Exit Sub
On Error Resume Next
Dim StartBox As Long
Dim StartBox2 As Long


Select Case UCase(Target.Value)


Case "NEW-BOX"
    StartBox = ActiveCell.Row
    StartBox2 = ActiveCell.Column
    MsgBox (StartBox)
    MsgBox (StartBox2)
    Selection.Offset(-1, 2).Select
    Selection.ClearContents
    Selection.Activate
    Selection.Offset(1, -2).Select

Case "RESTART-BOX"
    MsgBox (StartBox)
    MsgBox (StartBox2)

   If StartBox = 0 And StartBox2 = 0 Then
MsgBox "Cannot restart box without scanning a new box first!", vbCritical
ElseIf StartBox <> 0 And StartBox2 <> 0 Then
ActiveSheet.Range(Cells(StartBox, StartBox2), Cells(ActiveCell.Row, ActiveCell.Column)).ClearContents
End If


 End Select

End Sub

我扫描一个新的框,变量设置为正确的列和行,但是当我扫描重新启动框时,消息框都会出现0?为什么是这样?我需要将这些变量传递给我的代码以清除内容,但是由于某些原因,即使我正在设置它们,它们也不会出现在RESTART BOX中。

I scan a new box, and the variables set to the correct columns and row, but when I scan restart box, the message boxes both come up 0? Why is this? I need to pass these variables onto my code to clear the contents, but for some reason even though I am setting them they won't appear in 'RESTART-BOX' ?

推荐答案

我们需要更多的上下文才能提供一个确定的答案。您的代码是否处于某种循环中,或者是多次调用子或函数?

We need more context to be able to provide a definitive answer. Is your code in a loop of some sort or is this a sub or function being called multiple times?

如果后者那么你会得到一个StartBox和StartBox2的新副本创建每次你调用子/函数,所以他们不会保留的值。如果您将 dim 语句放在子程序或函数之外,那么它们将成为全局变量,并在每次调用子程序或函数时保留其值。

If the latter then you will get a new copy of StartBox and StartBox2 created each time you call the sub / function, so they won't retain the values. If you place the dim statements outside the sub or function then they will become global variables and will retain their values across each call to the sub or function.

这篇关于变量不设置在案例之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆