出于某种原因,在VBA中使用Select Case
语句时,一旦语句完成,我似乎丢失了我的变量值。
对于上下文,我试图按特定顺序捕获两个特定单元格上的双击动作。关键是隐藏功能,因此要运行该功能,用户必须首先双击单元格U35
,这应将egg
变量设置为1
。然后,如果用户双击单元格AF35
,并且egg
变量设置为1
,则该函数将运行。
我遇到的问题是双击单元格U35
后,egg
变量设置为null
,因此永远不会达到第二个Case
语句。< / p>
Private Sub Worksheet_Activate()
Dim egg
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Select Case egg
Case Is = 0
If Not Intersect(Target, Range("U35")) Is Nothing Then
MsgBox ("First action captured")
egg = 1
End If
Case Is = 1
If Not Intersect(Target, Range("AF35")) Is Nothing Then
MsgBox ("Second action captured")
egg = 0
End If
End Select
End Sub
答案 0 :(得分:1)
您需要在宏egg
之外全局声明变量Private Sub Worksheet_Activate()
,以便即使您离开本地上下文也能保持其值。
Dim egg As Integer '<-- global declaration (on top of module)
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'rest of your code
End Sub
答案 1 :(得分:0)
您可以声明一个全局变量,并在工作表上激活它,然后稍微修复Select Case
:
Dim egg As Long
Private Sub Worksheet_Activate()
egg = 0
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Debug.Print (egg)
Select Case egg
Case Is = 0
If Not Intersect(Target, Range("U35")) Is Nothing Then
MsgBox ("First action captured")
egg = 1
End If
Case Is = 1
If Not Intersect(Target, Range("AF35")) Is Nothing Then
MsgBox ("Second action captured")
' Do things here when they're clicked back-to-back
End If
egg = 0
End Select
End Sub
答案 2 :(得分:0)
<强>问题强>
“Worksheet_BeforeDoubleClick”无法识别“Worksheet_Activate”中的“egg”,因为它们是私有潜艇。
VBA中有两种类型的潜艇,私人和公共。有一些例外,一般来说,私人子内的信息无法从另一个子访问。
<强>将(S)强>
A)将变量定义为全局对象
B)在将要使用的子内部定义变量
A)将变量定义为全局对象
Public egg as Integer
Private Sub Worksheet_Activate()
egg = 0
'this is not necessary, you can set it inside BeforeDoubleClick
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
*your code*
End Sub
B)定义将在其中使用的变量
Private Sub Worksheet_Activate()
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim egg as Integer
egg = 0
*your code*
End Sub