【发布时间】:2016-02-03 23:44:45
【问题描述】:
先看看这个:
Dim Item1 As String
Dim Item2 As String
Dim Item3 As String
Dim Item4 As String
Dim Item5 As String
'Add text to these strings within the script
基本上,我有一个变量列表,这些变量使用一个简单的数字将它们分开。
我将这些变量打印到用户表单中,并将某些格式应用于这些表单。用户表单中也有相同的数字。
我在用户表单中的代码看起来像这样。
Form1.Caption = Item1
Form1.BackColor = 'Condition based on content of Item1
Label1.Width = 'Condition based on content of Item1
Form2.Caption = Item2
Form2.BackColor = 'Condition based on content of Item1
Label2.Width = = 'Condition based on content of Item1
'...and so on and so forth...
我实际上使用了 10 个变量,并且有一些 case 语句来处理上面提到的条件,所以代码变得相当冗长。
我想用一个简单的:
for i = 1 to 5
然后在用户表单中的 something 可能看起来像:
Form{i}.Caption = Item{i}
Form{i}.BackColor = 'Condition based on content of Item{i}
Label{i}.Width = 'Condition based on content of Item{i}
这有意义吗?我用于一些基本 PC 宏的程序“AutoHotKey”具有此功能 - 如果我记得格式很简单
form%_i
但显然那是 AHK 而这是 VBA!!
我什至不知道它是否可以完成,但我经常遇到这个问题,如果能得到一些解决方案会很好......
【问题讨论】:
-
您应该能够使用 & 形式 & 1 来连接。这就是你要找的东西吗?
-
你有什么理由避免像
Dim Items(1 to 10) As String这样的东西吗? -
John - 这实际上是我所做的 - 我有一个集合数组,其中包含我想要输出到用户表单的字段中的数据。但是,我不能(据我所知)将用户表单字段放入数组中。
-
Cptn_Hammer - 我试过你的技术,但不幸的是它不起作用。当我输入:
Form&i.Caption(其中“i”只是上面标注的整数)VBA 自动将其更改为Form& i.Caption但是当我尝试运行代码时,我得到:“编译错误:无效的限定符” -
Form1有目标Label1,为什么Form2有目标Label2,但没有Label1?以这种方式命名标签的目的是什么?
标签: vba loops variables for-loop indexing