提问人:Rayearth 提问时间:11/2/2023 最后编辑:Rayearth 更新时间:11/2/2023 访问量:44
在 for 循环 (VBA) 中动态命名和创建变量
Name and create variables dynamically in for loop (VBA)
问:
是否可以以任何其他方式在 VBA 中动态命名和分配变量?
Sub variables()
Dim lastCol As Long
lastCol = Sheet1.Cells.Find(What:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, LookAt:=xlWhole).Column
Dim i As Long
For i = 1 To lastCol
Dim colIndex(Cells(1, i).Value) As Long
colIndex(Cells(1, i)) = Cells(1, i).Column
Next i
End Sub
但是当我尝试运行它时,我看到此错误:
编译错误:
需要常量表达式
答:
1赞
Joel Coehoorn
11/2/2023
#1
不,你不能这样做。您可以做的是创建一个适当大小的数组,其中包含您需要的每个变量的位置。
评论
col
col(Cells(1, i)).Column
ReDim Preserve