使用循环 VBA 为变量赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41042931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign values to variable using loop VBA
提问by Jiminy Cricket
I have variables declared in VBA function like A1,A2,A3.....An
我在 VBA 函数中声明了变量,如 A1,A2,A3.....An
and assigned values to A1,A2,A3...An
并将值分配给 A1,A2,A3...An
now how can I update values in the variables using loop
现在如何使用循环更新变量中的值
Dim A1, A2, A3 As Integer, Tmp As String
A1 = 1
A2 = 2
A3 = 3
For i = 1 To 3
Debug.Print A & i
A & i = i+1 --- This line is not working
Next
How can I assign variables without using any arrays
如何在不使用任何数组的情况下分配变量
回答by Gary's Student
Re-consider using arrays:
重新考虑使用数组:
Sub marine()
Dim A(1 To 3) As Long
A(1) = 1
A(2) = 2
A(3) = 3
End Sub
回答by Jiminy Cricket
You could create a collection to do this, and later loop the collection or get the value by passing in the key (variable name)
您可以创建一个集合来执行此操作,然后循环该集合或通过传入键(变量名称)来获取值
Sub TestCollection()
Dim i As Long
Dim objCollection As New Collection
Dim varVariable As Variant
'Loop From 1 To 3. The Upper Bound Can Be Changed To Suit Your Needs
For i = 1 To 3
'Add The Key And Item To The Collection
'The First Parameter Is The Item (Value You Want To Store)
'The Second Parameter Is The Key (How You Access The Value, Like A Variable Name)
objCollection.Add i, "A" & i
Next i
'The Value Passed Into The Collection Is The Key - Which Is Like The Variable Name
Debug.Print objCollection("A1")
Debug.Print objCollection("A2")
Debug.Print objCollection("A3")
'Loop All Values
For Each varVariable In objCollection
Debug.Print varVariable
Next varVariable
End Sub