Eti*_*oël 3 arrays vba scope global-variables excel-vba
我需要在VBA中声明一个将由每个函数使用的数组.但是,我不能像在C++中那样将它声明为全局.
我的代码如下:
Option Explicit
Dim test(0 to 10) as String
test(0) = "avds"
test(1) = "fdsafs"
....
Run Code Online (Sandbox Code Playgroud)
以下概述了我想要做的事情.
public function store() as boolean
Worksheets("test").cells(1,1) = test(0)
End Function
Run Code Online (Sandbox Code Playgroud)
我该如何实现此功能?
对于全局声明,将Dim更改为Public,如下所示:
Public test(0 to 10) as String
Run Code Online (Sandbox Code Playgroud)
您可以这样调用(假设它在Module1中,否则将Module1更改为您命名的任何内容):
Module1.test(0) = "something"
Run Code Online (Sandbox Code Playgroud)
或者干脆:
test(0) = "something"
Run Code Online (Sandbox Code Playgroud)
你为什么不在课堂上创造一切?这就是毕竟发明课程的原因.
考虑一下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
Run Code Online (Sandbox Code Playgroud)
您可以添加所需的所有可以访问阵列的功能Store().与测试代码在工作表中
Public Sub Test()
Dim c As New Class1
c.Data(0) = "January"
Debug.Print c.Store(Cells(1, 1))
End Sub
Run Code Online (Sandbox Code Playgroud)
您还可以缓存它引用的单元格的位置,或者使用假定的命名参数,并且只在类初始化后提供对工作表的引用.