excel - VBA 对整个工作簿使用集合
问题描述
我需要在全局范围内使用 Collection 变量。但是,如果我将集合声明为公共,我只能在模块表或工作表中使用它。我需要为整个工作簿范围声明它以在工作簿函数、工作表函数和模块函数中使用它。
本工作簿
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")
推荐阅读
- java - 这段代码有什么错误?浏览器在此代码中显示“java.lang.NullPointerException”
- facebook - 如何将我的 Facebook 应用程序添加到我的 Facebook 群组?
- sql - 使用第一个表中的 2 个变量将一个表连接到另一个表并在 Select 中获取 2 个变量
- python-2.7 - python用管道运行shell命令
- javascript - 为什么在 CSV 中输入单词以搜索数据时,搜索框会变得滞后?
- python-3.x - 如何使用 pywinauto 在后台运行 WPF 应用程序
- java - 如何在 Java 中分配数组?
- laravel - 响应内容必须是实现 __toString()、“布尔”的字符串或对象
- c# - 在 LINQ 中使用 Where 删除查询
- reactjs - 尝试在空对象引用上调用虚拟方法 java.lang.String.android.content.Context.getPackageName()