我有一个变量" jobNo"根据用户输入,在1到5之间变化。我有另外5个变量:" J1C"," J2C"," J3C" ......
如何放置变量" jobNo"在其他5个变量中,以便当jobNo = 3时,例如我可以说:
J3C = 0
我试过了: " J" &安培; jobNo& " C" = 0
但得到错误。我该怎么办?
答案 0 :(得分:0)
我的建议与 @simoco 评论的内容相同。使用Array
:
Dim JC(1 to 5) As Double
JC(1) = 0
JC(2) = 0
JC(3) = 0
JC(4) = 0
JC(5) = 0
答案 1 :(得分:0)
你真的应该使用数组,不这样做,在这种情况下,编程非常糟糕......
但如果无法改变一切,你可以创建:
Sub VBP(jobNo, J1C, J2C, J3C, J4C, J5C)
Select Case jobNo
Case 1
J1C = 0
Case 2
J2C = 0
Case 3
J3C = 0
Case 4
J4C = 0
Case 5
J5C = 0
End Select
End Sub
然后像这样调用它:
VBP jobNo, J1C, J2C, J3C, J4C, J5C
答案 2 :(得分:0)
主要是因为我讨厌vba Array
你可以使用Collection
对象
Dim jobNos As New Collection
Sub intializejobNos
With jobNos
.Add 0, "J1C"
.Add 0, "J2C"
.Add 0, "J3C"
.Add 0, "J4C"
.Add 0, "J5C"
End With
End Sub
Sub changeJobNo(jobNo As String, val AS Variant)
OnError GoTo Handler
With jobNos
.Remove jobNo
.Add val, jobNo
End With
Exit_changeJobNo:
Exit Sub
Handler:
Msgbox "Job Number " & jobNo & " Does not exist in the collection."
GoTo Exit_changeJobNo
End Sub
Sub addJobNo(jobNo As Integer, val AS Variant)
jobNos.Add val, "J" & jobNo & "C"
End Sub
通过这种方式,您可以初始化jobNos
Collection
,而不需要ReDim
就可以完全改变大小,然后您可以根据需要更改值,然后您可以使用动态功能就像你想要的那样
Function getJobNo(jobNo AS Integer) As Variant
If jobNos.Count = 0 Then
initializejobNos
End If
getJobNo = jobNos("J" & jobNo & "C")
End Function
显然应该实施一些额外的错误处理,但我发现Collection
对象比使用本机VBA Array
更容易,更简洁。