VBA - 动态创建公共类型变量?
简单问一下,我的宏代码中包含所有这些静态设置的公共类型变量。这些应该代表 INI 文件的值。我希望的方式是代码都是动态的,基于 INI 文件中的内容。所以我不需要手动更新INI文件和后面的代码。
这是代码现在的样子。这是在它自己的模块内:
Public Type Fields
Firstname as String
Lastname as String
Username as String
End Type
我正在考虑使用 ReadIniSection 读取 INI 文件的整个部分,但似乎不可能在公共类型中执行此操作>。我说得对吗?有可能以某种方式解决这个问题吗?
Quick question, I've got all of these statically set Public Type
variables in my macro code. These are supposed to represent the values of an INI file. The way I would like it to be is that the code is all dynamic, based on what's in the INI file. So I don't need to manually update both the INI file and the code behind.
This is an outtake of the code the way it is now. This is inside it's own module:
Public Type Fields
Firstname as String
Lastname as String
Username as String
End Type
I was thinking of reading the entire section of the INI file using ReadIniSection
, but it seems as though it's not possible to do this within a Public Type
. Am I correct? Could it be possible to get around this somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 Scripting.Dictionary 对象(设置对 Scripting.Runtime 库的引用)。
存储:
读回:
假设您有具有单个值的唯一键名称。
http://msdn.microsoft.com/en -us/library/x4k5wbx4%28v=vs.85%29.aspx
蒂姆
Use a Scripting.Dictionary object (set a reference to the Scripting.Runtime library).
To store:
To read back:
That's assuming you have unique key names with single values.
http://msdn.microsoft.com/en-us/library/x4k5wbx4%28v=vs.85%29.aspx
Tim
也可以(但可能不建议)以编程方式向模块添加代码。由于 VBA 不支持反射,因此这是该语言中唯一的“动态”编码类型。这在紧要关头很有用。
请参阅下面的片段。
addCode
子函数采用标准模块的名称、Type
的名称以及包含字段定义的数组。它首先尝试删除现有的同名类型,然后添加新的类型定义。
It is also possible (but maybe not advisable) to add code to a module programatically. Since VBA does not support reflection, this is the only type of "dynamic" coding there is in the language. This is useful in a pinch.
See the snippet below. The
addCode
sub takes a standard module's name, aType
's name, and an array containing the definition of the fields.It first tries to delete the existing
Type
with the same name, and then adds the new type definition in.