Excel VBA对整个工作簿使用集合
我需要在全局范围内使用集合变量。但若我将集合声明为public,我只能在模块工作表或工作表中使用它。我需要为整个工作簿范围声明它,以便在工作簿函数、工作表函数和模块函数中使用它 此工作簿Excel VBA对整个工作簿使用集合,excel,vba,function,scope,global-variables,Excel,Vba,Function,Scope,Global Variables,我需要在全局范围内使用集合变量。但若我将集合声明为public,我只能在模块工作表或工作表中使用它。我需要为整个工作簿范围声明它,以便在工作簿函数、工作表函数和模块函数中使用它 此工作簿 Public foo As New Collection 工作表 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.ScreenUpdating = False row= Target.Row column= T
Public foo As New Collection
工作表
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = False
row= Target.Row
column= Target.Column
If Cells(row, 2).Value = "" Then
Exit Sub
Else
If Cells(row, 1).Value = "" Then
foo.Add row- 5
Cells(row, 1).Value = "X"
Cells(row, 2).Select
Cells(row, 14).Value = True
Else
foo.Remove row- 5
Cells(row, 1).Value = ""
Cells(row, 2).Select
Cells(row, 14) = False
End If
End If
Application.ScreenUpdating = True
End Sub
模块:
Sub col()
MsgBox foo.Count
End Sub
在标准模块中:
Private m_collection As Collection
Public Property Get TheCollection() As Collection
If m_collection Is Nothing Then Set m_collection = New Collection
Set TheCollection = m_collection
End Property
然后您可以在代码中的任何位置调用它
ModuleName.TheCollection.Add("whatever")
在标准模块中声明它。您能解释一下“标准模块”是什么意思吗?VBA使用表、标准、窗体和类模块。只有前一种类型与现有工作表或整个工作簿关联(
ThisWorkbook
)。必须插入其他三种类型。在VBE中,右键单击“Microsoft Excel对象”->“插入”并选择“模块”。这是一个标准的模块类型。