Sub在 VB6/VBA 中,您可以在特定方法或方法之外声明模块级变量Function。我之前在模块内部使用过Private并Public理解它们,如下所示:
Sub
Function
Private
Public
我注意到您可以使用DimandGlobal作为模块化变量的修饰符。当用作模块化字段的访问修饰符时, 和 分别Dim与和Global不同吗?如果是这样,它们有何不同?Private``Public
Dim
Global
Private``Public
在 VB6/VBA 中,Dim和Global在声明模块级变量时具有特定的角色,并且它们的范围和可见性Private确实有所不同。Public以下是每项的详细解释:
Public myVar As Integer
Private myVar As Integer
Dim myVar As Integer
Global myVar As Integer
下面是一个例子来说明这些关键字的用法:
' In Module1 Public myPublicVar As Integer ' Accessible from anywhere in the project Private myPrivateVar As Integer ' Accessible only within Module1 Dim myDimVar As Integer ' Accessible only within Module1, acts like Private Global myGlobalVar As Integer ' Accessible from anywhere in the project (VB6 only, not VBA) Sub TestModule1() myPublicVar = 10 myPrivateVar = 20 myDimVar = 30 myGlobalVar = 40 End Sub ' In Module2 Sub TestModule2() myPublicVar = 50 ' Accessible, since it's Public ' myPrivateVar = 60 ' Error: Not accessible, since it's Private to Module1 ' myDimVar = 70 ' Error: Not accessible, since it's Dim (Private) to Module1 myGlobalVar = 80 ' Accessible, since it's Global (VB6 only) End Sub
了解这些差异将帮助您在 VB6/VBA 项目中有效管理变量范围。