VBA 使用字符串作为变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20049357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:30:43  来源:igfitidea点击:

VBA use string as variable name

stringvbaexcel-vbaexcel

提问by RuneKAnd

I have workbooks with datasets (of varying lengths) from measurements in different rooms. I need to sort each datasets. My code finds the start and end rows of each dataset and stores them as StartRowRoom1, EndRowRoom1, StartRowRoom2, EndRowRoom2 etc.

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

I want to go through each dataset in a while loop like this.

我想像这样在 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

My problem is that the startRow and endRow variables are strings ("StartRowRoom1" and "EndRowRoom1", for n=1). so they cannot be used in Cells(). I want them to refer to the variables defined as integers. Does anyone have a solution?

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

采纳答案by Sam

This is what arrays are for.

这就是数组的用途。

You should declare your variables as

您应该将变量声明为

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]

Then you can access them as

然后你可以访问它们

startRow = StartRowRoom(n)
endRow = EndRowRoom(n)

using nas the index

使用n作为索引

回答by Antonio E.

I think you should try to store the StartRowRoom1 variables like Range type and use .offset() and .end() in getting that references.

我认为您应该尝试存储 StartRowRoom1 变量(如 Range 类型)并使用 .offset() 和 .end() 来获取该引用。

Then in your loop you don't need the Cells(,):

然后在你的循环中你不需要 Cells(,):

With Range(startRow, endRow) ...