【问题标题】:VBA use Collection for entire workbookVBA 对整个工作簿使用集合
【发布时间】:2020-11-21 02:20:17
【问题描述】:

我需要在全局范围内使用 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

【问题讨论】:

  • 在标准模块中声明。
  • 你能解释一下“标准模块”是什么意思吗?
  • VBA 使用工作表、标准、表单和类模块。只有第一个类型与现有工作表或整个工作簿相关联 (ThisWorkbook)。必须插入其他三种类型。在 VBE 中,右键单击“Microsoft Excel 对象”->“插入”并选择“模块”。这是一个标准的模块类型。

标签: excel vba function scope global-variables


【解决方案1】:

在标准模块中:

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")

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    相关资源
    最近更新 更多