vba 在循环中创建变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27784396/
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 05:42:24  来源:igfitidea点击:

Creating variables within a loop

excelvbaloopsvariablesexcel-vba

提问by arlederman

I'm working in VBA and I wanted to know if it was possible to create and name variables within a while loop. My goal is to look through a particular column in the worksheet and create variables whose values are the text within the cells of that column.

我正在使用 VBA,我想知道是否可以在 while 循环中创建和命名变量。我的目标是查看工作表中的特定列并创建变量,其值是该列单元格内的文本。

Ideally, the variable names and their values would be something along the lines of:

理想情况下,变量名和它们的值应该是这样的:

party1 = "Owner" 
party2 = "Contractor" 
party3 = "Subcontractor"

And so on a so forth based on an number of parties.

依此类推,基于多方。

So far I have:

到目前为止,我有:

Dim i As Integer, j As Integer
i = 2
j = 1
Do While Cells(i, 7).Value <> ""
    Dim partyName As String
    ' Pulls the text from the worksheet cell
    partyName = Cells(i, 7).Text
    Dim curNum As String
    curNum = CStr(j)
    Dim tempParty As String
    tempParty = "party" & curNum
    i = i + 1
    j = j + 1
Loop

I think this comes down to the question: How do I then get partyX to be the variable name and the variable value to be the string stored in partyName?

我认为这归结为一个问题:我如何让 partyX 成为变量名,并将变量值作为存储在 partyName 中的字符串?

Thisseems like it's along the lines of what I'm looking for, but it doesn't quite answer my question. Also, I recognize there may be issues with the scope of these variables, but I can't think of any other way to do this.

似乎符合我正在寻找的内容,但它并不能完全回答我的问题。此外,我认识到这些变量的范围可能存在问题,但我想不出任何其他方法来做到这一点。

采纳答案by Chrismas007

IF you need to turn a NAME into a NUMBER using Select Case:

如果您需要使用以下方法将 NAME 转换为 NUMBER Select Case

Dim CurRow As Long, LastRow As Long
LastRow = Cells(Rows.Count, 7).End(xlUp).Row

For CurRow = 1 to LastRow
    partyName = Cells(i, 7).Value
    Select Case partyName
        Case "Owner"
            partyNum = 1
        Case "Contractor"
            partyNum = 2
        Case "Subcontractor"
            partyNum = 3
        Case Else
    End Select
    'Do something with partyNum here
Next CurRow

If you need to turn a NUMBER into a NAME using Select Case:

如果您需要使用以下方法将 NUMBER 转换为 NAME Select Case

Dim CurRow As Long, LastRow As Long
LastRow = Cells(Rows.Count, 7).End(xlUp).Row

For CurRow = 1 to LastRow
    partyNum = Cells(i, 7).Value
    Select Case partyNum
        Case 1
            partyName = "Owner"
        Case 2
            partyName = "Contractor"
        Case 3
            partyName = "Subcontractor"
        Case Else
    End Select
    'Do something with partyName here
Next CurRow