简体   繁体   English

在多个宏中使用变量

[英]Using variables in multiple macros

Can someone explain what am I doing wrong here.有人可以解释我在这里做错了什么。 Excel doesn't seem to set the variable value if I run the second macro before the first one.如果我在第一个宏之前运行第二个宏,Excel 似乎没有设置变量值。 I would like to set the values just once and use them in multiple macros.我想只设置一次值并在多个宏中使用它们。 I have 6 macros that will be using the same values.我有 6 个宏将使用相同的值。 The code included below is a short code I use to test.下面包含的代码是我用来测试的短代码。

Option Explicit

Dim Test As String

Sub sub1()

Test = "Test"
MsgBox Test

End Sub

Sub sub2()

MsgBox Test

End Sub

This is the popup i get if the second macro is executed before the first one.如果第二个宏在第一个宏之前执行,这是我得到的弹出窗口。

在此处输入图像描述

Just call the second macro from the first.只需从第一个宏调用第二个宏。 Otherwise Test will not be assigned a value.否则 Test 不会被赋值。

You can read about scope here .您可以在此处阅读有关 scope 的信息。

Dim Test As String

Sub sub1()

Test = "Test"
MsgBox Test
sub2 'or call sub2

End Sub

Or you can use a Constant , eg或者你可以使用一个Constant ,例如

Public Const Test As String = "Test"

(see my edit below - the original answer doesn't answer the question you asked properly) (请参阅下面的编辑 - 原始答案没有正确回答您提出的问题)

You can set it as a public variable您可以将其设置为公共变量

Option Explicit

Public Test As String

Sub sub1()

    Test = "Test"
    MsgBox Test

End Sub

Sub sub2()

    MsgBox Test

End Sub

Or call sub2 from sub1 with a parameter或者使用参数从 sub1 调用 sub2

Sub sub1()

    Test = "Test"
    MsgBox Test
    'call the second sub with the Test variable here
    sub2 Test

End Sub

Sub sub2(test as string)

    MsgBox test

End Sub

or have Sub1 be a function and return the value或者让 Sub1 成为 function 并返回值

Function sub1()

    Test = "Test"
    MsgBox Test
    'call the second sub with the Test variable here
    sub1 = Test

End Function

Sub sub2()
    test = sub1()
    MsgBox test

End Sub

EDIT:编辑:

Or you could wrap it all in another sub so you are able to define the public variable或者你可以将它全部包装在另一个子中,这样你就可以定义公共变量

Public Test as string 

Sub sub1()

    MsgBox Test

End Sub

Sub sub2()

    MsgBox Test

End Sub

Sub run()
    Test = "Test"
    sub1()
    sub2()

End Sub

If you want a variable to keep its value for the whole excel session (ie a static variable) use the Global keyword如果您希望一个变量为整个 excel session(即 static 变量)保留其值,请使用Global关键字

Global Test As String

Remember, one of your procedures must assign a value to it.请记住,您的一个过程必须为其分配一个值。 Otherwise it will have a value of ""否则它的值为""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM