【问题标题】:VBA: Arrays and Global Variable DeclarationsVBA:数组和全局变量声明
【发布时间】:2026-01-26 21:15:01
【问题描述】:

我需要在 VBA 中声明一个将被每个函数使用的数组。但是,我不能像在 C++ 中那样将其声明为全局变量。

我的代码如下:

Option Explicit
 Dim test(0 to 10) as String

 test(0) = "avds"
 test(1) = "fdsafs"
 ....

以下概念化了我正在尝试做的事情。

 public function store() as boolean
  Worksheets("test").cells(1,1) = test(0)
 End Function

我怎样才能实现这个功能?

【问题讨论】:

    标签: arrays excel global-variables scope vba


    【解决方案1】:

    对于全局声明,将 Dim 更改为 Public,如下所示:

    Public test(0 to 10) as String
    

    您可以这样称呼它(假设它在 Module1 中,否则将 Module1 更改为您命名的任何名称):

    Module1.test(0) = "something"
    

    或者简单地说:

    test(0) = "something"
    

    【讨论】:

    • 这种作品。您仍然无法在 SubFunction 之外定义 test 数组的值。
    【解决方案2】:

    您为什么不在一个类中创建所有内容?这就是为什么要发明类的原因。

    考虑Class1 定义

    Option Explicit
    
    Private m_data() As String
    
    Private Sub Class_Initialize()
        ReDim m_data(0 To 10)
    End Sub
    Private Sub Class_Terminate()
        Erase m_data
    End Sub
    
    Public Property Get Count() As Integer
        Count = UBound(m_data) - LBound(m_data) + 1
    End Property
    
    Public Property Get Data(index As Integer) As String
        Data = m_data(index)
    End Property
    
    Public Property Let Data(index As Integer, value As String)
        m_data(index) = value
    End Property
    
    Public Function Store(rng As Range) As Boolean
        Store = (rng.value = m_data(0))
    End Function
    

    您可以添加所有想要访问数组的函数,就像Store() 一样。 与工作表中的测试代码

    Public Sub Test()
        Dim c As New Class1
    
        c.Data(0) = "January"
    
        Debug.Print c.Store(Cells(1, 1))
    End Sub
    

    您还可以缓存它所引用的单元格的位置,或者使用假定的命名参数,并且只在类初始化后提供一次对工作表的引用。

    【讨论】:

      【解决方案3】:

      您可以使用Public 关键字来声明您需要在任何模块中访问的变量。

      请记住,在 vba 中,您不能在过程之外声明变量或代码。

      更多信息请参见here

      【讨论】:

        【解决方案4】:

        我有一个比课程轻一点的建议(尽管课程是一个很好的建议)

        选项 1

        将所需的常量数组定义为分隔字符串常量:

        Public Const cstrTest = "String 1;String 2; String 3; String 4; String 5; String 6"
        

        接下来,只要您需要它,只需使用 Split 以最少的代码创建一个数组:

        Dim arrStrings
        arrStrings = Split (cstrTest, ";")
        

        选项 2

        您可以替换(或与选项 1 结合)一个简单的公共函数

        Public Function constStringArray() As String()
        
            constStringArray = Split (cstrTest, ";")
        
        End Function
        

        那么,在使用中……

        Dim arrStrings
        
        'Option 1 example
        arrStrings = Split (cstrTest, ";")
        
        'Option 2 example
        arrStrings = constStringArray()
        

        【讨论】:

          【解决方案5】:

          可以通过Static Property 非常直接地做到这一点(通过全局初始化),而无需创建类或字符串解析 - 如详细描述和示例here

          【讨论】: