我有一个' For循环'在VBA中有两个可变元素。一个是数字,一个是单词。想象一下,最终输出如下所示:
Result[1].Apple
Result[1].Orange
Result[1].Banana
Result[2].Apple
Result[2].Orange
Result[2].Banana
对于1
和2
,在我的函数开头,我使用:i = 1 to 2
。在我的函数结束时,我使用:Next i
。
Sub Button1_Click()
For i = 0 To 5
'want to cycle through .apple, .orange, .banana after going through i values. presumably calling this variable Fruit
MyConcatenatedString = "Result[" & i & "]." & Fruit
If TypeName(Data) = "Error" Then
If MsgBox("Error reading "Result[" & i & "]." & Fruit & _
"Continue with read?", vbYesNo + vbExclamation, _
"Error") = vbNo Then Exit For
Else
'no error, put data in excel cell
End If
'send data to cell and increment i
Cells(4, 2 + i) = MyConcatenatedString
Next i
End Sub
我如何通过Apple
,Orange
和Banana
使我的功能循环,例如我使用1
循环2
和i
?
答案 0 :(得分:1)
您可以使用数组来定义第二个变量元素:
Dim A() : Redim A(2))
A(0)="Apple" : A(1)="Orange" : ....
并循环使用For k = LBound(A) to UBound(A)
所以最后应该看起来像这样:
Sub test_Karhu()
Dim TpStr As String
Dim A(): ReDim A(2)
A(0) = "Apple": A(1) = "Orange": A(2) = "Banana"
For i = 1 To 2
For k = LBound(A) To UBound(A)
TpStr = TpStr & "Result[" & i & "]." & A(k) & vbCrLf
Next k
Next i
MsgBox TpStr
End Sub