在另一个Sub中调用多个变量

时间:2019-04-13 13:27:33

标签: excel vba

当我尝试在另一个子例程中使用在子例程中创建的变量时遇到问题。 在以下示例中,我在Sub part0 中创建变量 Power_Origine,Power_Destination,... ,我可以在Sub part1 中使用其中一个变量>,但我不能在一个子例程( part2 )中使用多个变量。

Sub part0()

Power_Origine = 1
Description_Origine = 2
KnownUser_Origine = 3
Power_Destination = 1
Description_Destination = 2
KnownUser_Destination = 3


part1 (Power_Destination)
part2 (Power_Origine, Power_Destination, Description_Destination, KnownUser_Destination)
'part2 Power_Origine, Power_Destination, Description_Destination, KnownUser_Destination ' This does not work either

End Sub


Sub part1(Power_Destination As Integer)
MsgBox Power_Destination
End Sub


Sub part2(Power_Origine As Integer, Power_Destination As Integer, Description_Destination As Integer, KnownUser_Destination As Integer)
MsgBox "Hello " & Power_Destination & Description_Destination
End Sub

如何在子例程 part2 中调用这4个变量( Power_Origine,Power_Destination,Description_Destination,KnownUser_Destination )?

谢谢。

1 个答案:

答案 0 :(得分:1)

  

但是我不能在一个子例程(第2部分)中使用多个变量

可以。只需删除()。变成

part2 Power_Origine, Power_Destination, Description_Destination, KnownUser_Destination 

或使用

Call part2(Power_Origine, Power_Destination, Description_Destination, KnownUser_Destination)

与上述相同。由于您在Power_Origine As Integer, Power_Destination As Integer, Description_Destination As Integer, KnownUser_Destination As Integer中声明了part02,但在part0中却声明了Variants,因此您可能仍然会收到错误消息。在Integer中将它们声明为part0,它将起作用:)

Sub part0()
    Dim Power_Origine As Integer
    Dim Description_Origine  As Integer
    Dim KnownUser_Origine  As Integer
    Dim Power_Destination  As Integer
    Dim Description_Destination As Integer
    Dim KnownUser_Destination  As Integer

    Power_Origine = 1
    Description_Origine = 2
    KnownUser_Origine = 3
    Power_Destination = 1
    Description_Destination = 2
    KnownUser_Destination = 3

    part1 Power_Destination
    part2 Power_Origine, Power_Destination, Description_Destination, KnownUser_Destination
End Sub

Sub part1(Power_Destination As Integer)
    MsgBox Power_Destination
End Sub

Sub part2(P_Orig As Integer, P_Dest As Integer, D_Dest As Integer, K_Dest As Integer)
    MsgBox "Hello " & P_Dest & D_Dest
End Sub

您可能还想阅读Passing Variables By Reference And By Value