Sub Test()
Dim ABC As Integer
ABC = [A1+(B2*C3)] 'Works fine
Dim i as Long
Dim XYZ As Integer
For i = 1 to 100
XYZ = [A & i +(B & (i + 1) * C & (i + 2))] 'Not working - how to resolve this?
'Rest of VBA code
Next i
End Sub
答案1
[]
Application.Evaluate
是使用变量时需要使用Application.Evaluate("")
和解析字符串的简写:
XYZ = Application.Evaluate("A" & i & "+(B" & (i + 1) & "* C" & (i + 2) & ")")
但Application.Evaluate
假设活动工作表和更好的用途是使用Worksheet.Evaluate
以确保使用正确的工作表:
XYZ = WorkSheet("Sheet1").Evaluate("A" & i & "+(B" & (i + 1) & "* C" & (i + 2) & ")")
但在这种情况下使用 Evaluate 很慢。相反,只需使用 Range 对象本身即可。
With Worksheet("Sheet1")
XYZ = .Range("A" & i) + (.Range("B" & i + 1) * .Range("C" & i + 1))
End With