string - VBA 使用字符串作为变量名

标签 string vba excel

我有来自不同房间测量的数据集(不同长度)的工作簿。我需要对每个数据集进行排序。
我的代码找到每个数据集的开始行和结束行,并将它们存储为 StartRowRoom1、EndRowRoom1、StartRowRoom2、EndRowRoom2 等。

我想像这样在一个while循环中遍历每个数据集。

Dim StartRowRoom1 As Integer
Dim StartRowRoom2 As Integer
Dim EndRowRoom1 As Integer
Dim EndRowRoom2 As Integer

n = 1

While n < NumberOfRooms
    startRow = "StartRowRoom" & n
    endRow = "EndRowRoom" & n

    With Range(Cells(startRow, 4), Cells(endRow, 4))
        .FormulaR1C1 = "=RC[-2]+RC[-1]"
        #sorting and graph creation
    End With
    n = n + 1
Wend

我的问题是 startRow 和 endRow 变量是字符串(“StartRowRoom1”和“EndRowRoom1”,对于 n=1)。所以它们不能在 Cells() 中使用。我希望他们引用定义为整数的变量。
有没有人有办法解决吗?

最佳答案

这就是数组的用途。

您应该将变量声明为

Dim StartRowRoom(1 to 2) As Integer
Dim EndRowRoom(1 to 2) As Integer

StartRowRoom(1) = [your value here]
StartRowRoom(2) = [your value here]

EndRowRoom(1) = [your value here]
EndRowRoom(2) = [your value here]

然后你可以访问它们
startRow = StartRowRoom(n)
endRow = EndRowRoom(n)

使用 n作为指标

关于string - VBA 使用字符串作为变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20049357/

相关文章:

arrays - “VBA Loop Until - Array” 数组填满后我想立即退出

vba - 单击 CommandButton 以显示带有 URL 链接的用户窗体

javascript - 从网站上读取信息并存储在 excel 文件中

python - 将 Pandas Dataframe 和 numpy 数组写入通用 Excel 文件

c++ - 如何将多个字符组合成一个字符串?

c++ - 迭代一个字符串,但将分隔符保留在子字符串中,包括其他规则

java - 如何解析具有自定义逻辑条件的字符串?

python - 如何根据位置替换字符串中多个相同的字符?

excel - 在 VBA 中循环使用具有相似名称结构的工作表

excel - 如何使用 Excel 文件中的文本数据列作为 x 轴进行绘图?