我的问题是我的变量和指定值如何用于所有模块,例如:
这是声明全局模块:
sub global()
public A as integer
A=3
end sub
这是第一个模块(对于sheet1):
sub first()
if Sheet1.Cells(1, "A") > 100 then
Sheet3.Cells(A, "A") = Sheet1.Cells(1, "B").Value
A=A+1
eng sub
这是第二个模块(对于sheet2):
sub second()
if Sheet2.Cells(1, "A") > 100 then
Sheet3.Cells(A, "A") = Sheet2.Cells(1, "B").Value
A=A+1
end sub
*我已将每个工作表的模块文件分开,例如sheet1与module1和sheet2与module2。
所以我希望当第一个或第二个模块中的A
和将返回到global()A值时。
答案 0 :(得分:0)
在模块中声明子变量或函数外的Public A As Integer
变量,可以实现所需的功能。
Public A As Integer
Sub SetGlobal()
A = 3
End Sub
然后在其他地方:
Sub first()
A = A + 3
MsgBox A
End Sub
通常,您无法命名子Global
,因为它是VBE
使用的名称。
如果您想拥有公共变量的最小值,那么您可以考虑创建一个具有Get
- 属性条件的类。如果最小值为3
,那么该类应如下所示:
Option Explicit
Private m_lA As Long
Public Property Get A() As Long
A = m_lA
If A < 3 Then A = 3
End Property
Public Property Let A(ByVal lNewValue As Long)
m_lA = lNewValue
End Property
你可以从这样的模块中调用它:
Option Explicit
Public myVar As New publicA
Public Sub TestMe()
Debug.Print myVar.A
myVar.A = myVar.A * 30
Debug.Print myVar.A
End Sub
答案 1 :(得分:0)
根据对Vityata's answer的评论和对问题的修改:
Module1
Option Explicit
Public A as Long
'Long and Integer use the same amount of Memory in VBA,
' so there is no reason not to use Long
Sub getglobal()
A=3
End Sub
第2单元
Option Explicit
Sub first()
If Sheet1.Cells(1, "A") > 100 Then
Sheet3.Cells(A, "A") = Sheet1.Cells(1, "B").Value
End If
Module1.A=Module1.A+1
End Sub
第3单元
Option Explicit
Sub second()
If Sheet2.Cells(1, "A") > 100 Then
Sheet3.Cells(A, "A") = Sheet2.Cells(1, "B").Value
End If
Module1.A=Module1.A+1
End Sub