VBA - 在更多模块中使用相同的变量

时间:2015-05-23 09:00:55

标签: excel vba excel-vba module

我想要三个总结如下的模块:

FIRST MODULE

Sub settings()
 Dim variable1,variable2,variable3,_
  variable4,variable5,variable6 as String

 variable1="Stack"
 variable2="Overflow"
 variable3="Best"
 variable4="Site"
 variable5="Ever"
 variable6="I love it!"
End sub

第二模块

Sub module2()
 'LINE CODE THAT CALLS "settings" MODULE (I want to know it!)

 'my sub that uses the six-variables above
End sub

第三个模块

Sub module3()
 'LINE CODE THAT CALLS "settings" MODULE (I want to know it!)

 'another sub that uses the six-variables above
End sub

提前致谢。

的Fabio

2 个答案:

答案 0 :(得分:0)

您应该将模块设为:

第1单元:

Public variable1, variable2, variable3, variable4, variable5, variable6 As String
Sub settings()
  variable1 = "Stack"
  variable2 = "Overflow"
  variable3 = "Best"
  variable4 = "Site"
  variable5 = "Ever"
  variable6 = "I love it!"
End Sub

第2单元:

Sub module2()
  Module1.settings
  MsgBox "value : " & Module1.variable1

End Sub

在第2单元中,您必须首先运行settings()子例程,然后使用变量,因为变量的赋值发生在settings()

答案 1 :(得分:0)

似乎这些变量总是保持相同的值,如果是这种情况,那么我建议使用下面的代码来声明公共常量(参见https://msdn.microsoft.com/en-us/library/office/gg264636.aspx

Public Const kConst1 As String = "Stack"
Public Const kConst2 As String = "Overflow"
Public Const kConst3 As String = "Best"
Public Const kConst4 As String = "Site"
Public Const kConst5 As String = "Ever"
Public Const kConst6 As String = "I love it!"

将常量用作:

Sub Test_Const()
Debug.Print kConst1, kConst2, kConst3, kConst4, kConst5, kConst6
End Sub