我在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似乎与我正在寻找的一致,但它并没有完全回答我的问题。此外,我认识到这些变量的范围可能存在问题,但我想不出有任何其他方法可以做到这一点。
答案 0 :(得分:1)
如果您需要使用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
将号码转换为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