Vba 我想通过引用另一个变量的内容来调用一个特定变量

Vba 我想通过引用另一个变量的内容来调用一个特定变量,vba,loops,variables,for-loop,indexing,Vba,Loops,Variables,For Loop,Indexing,首先看看这个: 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 基本上,我有一个变量列表,使用一个简单的数字将它们分开 我正在将这些变量打印到用户表单中,并将一些格式应用到这些表单中。用户表单中也有相同的数字 我在userform中的代码看起来像这样 F

首先看看这个:

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
基本上,我有一个变量列表,使用一个简单的数字将它们分开

我正在将这些变量打印到用户表单中,并将一些格式应用到这些表单中。用户表单中也有相同的数字

我在userform中的代码看起来像这样

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
然后是userform中的一些内容,可能如下所示:

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


我不知道它是否可以实现,但我经常遇到这个问题,如果能得到一些解决方案就好了…

对于控件,您可以使用以下方法:

myForm.Controls(“Label”&i).Width

有关引用用户表单的信息,请参见:


您应该能够在表单&1中使用&as来连接。这就是你要寻找的吗?有没有任何理由让你避免像
Dim Items(1到10)这样的东西作为String
?John-这实际上就是我所做的-我有一个集合数组,其中包含我想要输出到用户表单字段中的数据。但是,据我所知,我无法将用户表单字段放入数组中。Cptn_Hammer-我尝试了您的技术,但不幸的是,它不起作用。当我键入:
Form&I.Caption
(其中“I”只是上面标注的整数)时,VBA会自动将其更改为
Form&I.Caption
,但是当我尝试运行代码时,我会得到:“编译错误:无效限定符”
Form1
有目标
Label1
,为什么
Form2
有目标
Label2
,但不是
标签1
?这样命名标签的目的是什么?你赢了!!!这非常有效。它并不能解决我遇到的每一个问题,但它可以解决这个问题!谢谢
Dim frm As Object

On Error Resume Next
Set frm = UserForms.Add("UserForm" & 1)
On Error GoTo 0

If Not frm Is Nothing Then
    Debug.Print "Got form: " & frm.Caption
Else
    Debug.Print "No form with that name!"
End If