在循环中创建变量
Creating variables within a loop
我在 VBA 工作,我想知道是否可以在 while 循环中创建和命名变量。我的目标是查看工作表中的特定列并创建变量,其值是该列单元格中的文本。
理想情况下,变量名称及其值应类似于:
party1 = "Owner"
party2 = "Contractor"
party3 = "Subcontractor"
依此类推。
到目前为止我有:
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
我认为这归结为一个问题:我如何让 partyX 成为变量名,变量值成为存储在 partyName 中的字符串?
This 似乎符合我的要求,但它并没有完全回答我的问题。另外,我知道这些变量的范围可能存在问题,但我想不出任何其他方法来做到这一点。
如果您需要使用 Select Case
将 NAME 转换为 NUMBER:
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
如果您需要使用 Select Case
将 NUMBER 转换为 NAME:
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
我在 VBA 工作,我想知道是否可以在 while 循环中创建和命名变量。我的目标是查看工作表中的特定列并创建变量,其值是该列单元格中的文本。
理想情况下,变量名称及其值应类似于:
party1 = "Owner"
party2 = "Contractor"
party3 = "Subcontractor"
依此类推。
到目前为止我有:
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
我认为这归结为一个问题:我如何让 partyX 成为变量名,变量值成为存储在 partyName 中的字符串?
This 似乎符合我的要求,但它并没有完全回答我的问题。另外,我知道这些变量的范围可能存在问题,但我想不出任何其他方法来做到这一点。
如果您需要使用 Select Case
将 NAME 转换为 NUMBER:
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
如果您需要使用 Select Case
将 NUMBER 转换为 NAME:
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