VBA 如何在 subs 之间使用变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40904181/
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
VBA How to use a variable between subs?
提问by Ricky
I'm pretty new to VBA and I don't know how to use a variable between subs. The code should be pretty self explanatory:
我对 VBA 很陌生,我不知道如何在 subs 之间使用变量。代码应该是不言自明的:
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim strWeapon As String
If Target.Address = "$I" Then
MsgBox "You pick up a sword"
strWeapon = "Sword"
ElseIf Target.Address = "$I" Then
MsgBox "You pick up a magic staff"
strWeapon = "Magic"
ElseIf Target.Address = "$I" Then
MsgBox "You pick up a bow and arrows"
strWeapon = "Bow"
End If
End Sub
Public Sub CommandButton1_Click()
If strWeapon = "Magic" Then
UserForm1.Show
ElseIf strWeapon = "Sword" Then
UserForm2.Show
ElseIf strWeapon = "Bow" Then
UseForm2.Show
End If
End Sub
Is there a way I can use strWeapon in both subs? I get an error for not defining the variable strWeapon in the second sub. Thank you!
有没有办法可以在两个潜艇中使用 strWeapon ?我因未在第二个子项中定义变量 strWeapon 而出现错误。谢谢!
回答by User632716
You have a couple of options.
你有几个选择。
You can use a public variable as shai rado has mentioned- this is probably easiest, however you should limit the use of public variables where possible.
You can pass the variable from one sub to another like this:
sub Main() dim strWeapon as string strWeapon = "Fork" WillIWin strWeapon end sub sub WillIWin(strWeapon as string) select case strWeapon case "Gun" msgbox "Probably" case "Sword" msgbox "unlikely" case "Fork" Msgbox "Goodluck" end select End SubAlternatively if you have multiple variables to pass, you might be better with a class, this option takes more work than I'm willing to put in here, but CPearson has a good introductory course for them.
您可以使用 shai rado 提到的公共变量 - 这可能是最简单的,但是您应该尽可能限制公共变量的使用。
您可以像这样将变量从一个子传递到另一个子:
sub Main() dim strWeapon as string strWeapon = "Fork" WillIWin strWeapon end sub sub WillIWin(strWeapon as string) select case strWeapon case "Gun" msgbox "Probably" case "Sword" msgbox "unlikely" case "Fork" Msgbox "Goodluck" end select End Sub或者,如果你有多个变量要传递,你可能会更好地使用一个类,这个选项需要比我愿意在这里放的更多的工作,但是 CPearson 有一个很好的入门课程。
回答by user1
yes!
是的!
Public strWeapon as String
Public strWeapon as String
At the top of any module, do the following:
在任何模块的顶部,执行以下操作:
tpye Option Explicitthen immediately below, put the Public declaration.
this can then be used in any other subroutine OR module within your excel project
类不Option Explicit那么正下方,把公共声明。然后可以在您的 excel 项目中的任何其他子程序或模块中使用它

