如何在循环中声明变量名?例如,我需要声明Combo1Count,Combo2Count,Combo3Count等等:
Dim i As Integer
For i = 1 To 6
Dim Combo & i & Count as Integer
Next i
然后我将需要参考这些变量,例如:
For i = 1 To 6
If Combo & i & Count > 0 ....
Next i
答案 0 :(得分:0)
范围不是VBA中的问题。问题是......你做不到。
解决方法是使用Select Case:
Dim i As Integer
For i = 1 To 6
Select Case 1
Dim Combo1 As Integer
Select Case 2
Dim Combo2 As Integer
' ....
Select Case 6
Dim Combo6 As Integer
End Select
Next i
当然没有意义。所以使用:
Dim Combo1 As Integer
Dim Combo2 As Integer
' ....
Dim Combo6 As Integer
答案 1 :(得分:-1)
循环中定义的变量受每种语言的“范围”规则的约束。对于VBA,您可以在此处阅读更多内容:Scope of variables in Visual Basic for Applications - Microsoft
因此,循环中定义的任何变量或条件语句(等)都不能在该范围之外访问。如果您希望变量在循环中接收值,那么您应该在循环声明之上将其调暗。然后可以根据需要在代码中稍后访问它(甚至在循环中)
答案 2 :(得分:-1)
您可以使用数组来存储您的计数值。
dim myArray(1 to 6) as Variant
dim i as Integer
myArray(1) = combo1Count
myArray(2) = combo2Count
...
'to acces the Values simply use
for i = 1 to 6
if myArray(i) > 0 then ...
next i