VBA:数组和全局变量声明
我需要在 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
我怎样才能实现这个功能?
I need to declare an array in VBA that will be used by every function. However, I cannot declare it as a global as I would do in C++.
My code is as follows:
Option Explicit
Dim test(0 to 10) as String
test(0) = "avds"
test(1) = "fdsafs"
....
The following conceptualizes what I am trying to do.
public function store() as boolean
Worksheets("test").cells(1,1) = test(0)
End Function
How can I achieve this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于全局声明,将 Dim 更改为 Public,如下所示:
您可以这样调用(假设它位于 Module1 中,否则将 Module1 更改为您命名的任何名称):
或者简单地:
For global declaration, change Dim to Public like so:
You can call this like (assuming it is in Module1, else change Module1 to whatever you've named it):
Or simply:
为什么不在类中创建所有内容呢?这就是为什么要发明类的原因。
考虑
Class1
定义您可以添加所有您想要的可以访问数组的函数,就像
Store()
一样。的单元格的位置,或者使用假定的命名参数,并且仅在类初始化后提供对工作表的引用一次。
您还可以缓存引用
Why wouldn't you create everything in a class? That's the reason why classes where invented after all.
Consider the
Class1
definitionYou can add all the functions you want that can access your array just like
Store()
.with the test code in a worksheet of
You can also cache the location of the cell where it is referencing, or used an assumed named argument and only supply a reference to the worksheet once after class initialization.
您可以使用
Public
关键字来声明需要在任何模块中访问的变量。请记住,在 vba 中,您不能在过程之外声明变量或代码。
有关详细信息,请参阅此处
You can use the
Public
keyword to declare a variable that you need to access in any module.Remember that in vba you cannot declare variables or code outside of procedures.
See here for more information
我有一个比类更轻的建议(尽管类是一个很好的建议)
选项 1
将所需的常量数组定义为分隔字符串常量:
接下来,每当您需要它时,只需使用 Split 来用最少的代码创建一个数组:
选项 2
您可以替换(或与选项 1 结合)一个简单的公共函数
那么,在使用中...
I have a recommendation that is a bit lighter than a class (although class is a great recommendation)
Option 1
Define your desired constant array as a delimited string constant:
Next, whenever you need it just use Split to create an array with minimal code:
Option 2
You might replace (or combine with Option 1) a simple public function
So then, in use...
人们可以通过
静态属性
非常直接地做到这一点(通过全局初始化),而无需创建类或字符串解析 - 如详细描述和示例这里one can do it (with global initialization) via
Static Property
quite straight-forward without creating a class or string parsing - as described in detail and with examples here