在 for 循环 (VBA) 中动态命名和创建变量

Name and create variables dynamically in for loop (VBA)

提问人:Rayearth 提问时间:11/2/2023 最后编辑:Rayearth 更新时间:11/2/2023 访问量:44

问:

是否可以以任何其他方式在 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

但是当我尝试运行它时,我看到此错误:

编译错误:

需要常量表达式

Excel VBA 变量 动态

评论

0赞 user3598756 11/2/2023
使用 ReDim 而不是 Dim。这些括号内使用的值必须为长型
0赞 BigBen 11/2/2023
里面有什么?你期望这里的输出是什么?colcol(Cells(1, i)).Column
0赞 PeterT 11/2/2023
如果要保留已存储在数组中的值,请使用 .ReDim Preserve

答:

1赞 Joel Coehoorn 11/2/2023 #1

不,你不能这样做。您可以做的是创建一个适当大小的数组,其中包含您需要的每个变量的位置。