我想在一个模块中的 VBA 中定义一个全局变量,并在其他 VBA 模块中使用它。
我正在尝试关注:How do I declare a global variable in VBA?
我创建了一个名为“GlobalVariables”的新模块,首先声明了公共(public)变量,然后在函数中设置它们的值(尝试在开放代码中执行此操作会导致错误)。我的代码如下。
但是 Global
变量 StartYear 似乎不适用于其他 VBA 模块。我究竟做错了什么?
Option Explicit
Public StartYear As Integer
Public BaseYear As Integer
Function DeclareGlobalVariables()
StartYear = ActiveWorkbook.Worksheets("RunModel").Range("StartYear").Value
BaseYear = ActiveWorkbook.Worksheets("RunModel").Range("BaseYear").Value
End Function
最佳答案
Function
应该是 Sub
因为它不返回任何东西。 所以我建议以下
模块 1
Option Explicit
Public StartYear As Long
Public BaseYear As Long
Public Function InitializeGlobalVariables() As Boolean
InitializeGlobalVariables = True
With ActiveWorkbook.Worksheets("RunModel").Range("StartYear")
If IsYear(.Value) Then
StartYear = CLng(.Value)
Else
InitializeGlobalVariables = False
MsgBox "StartYear needs to be a number"
End If
End With
With ActiveWorkbook.Worksheets("RunModel").Range("BaseYear")
If IsYear(.Value) Then
BaseYear = CLng(.Value)
Else
InitializeGlobalVariables = False
MsgBox "BaseYear needs to be a number"
End If
End With
End Function
'validate if the input value is a valid year
Private Function IsYear(ByVal InputValue As Variant) As Boolean
If IsNumeric(InputValue) Then
If CLng(InputValue) = InputValue And _
InputValue > 0 And InputValue < 9999 Then 'integer not decimal AND 4 digit year
IsYear = True
End If
End If
End Function
您可以访问任何其他模块中的变量,例如:
模块二
Option Explicit
Public Sub TestOutput()
'before using the variables test if they are initialized (not 0)
If StartYear = 0 Or BaseYear = 0 Then
'they are not initalized so initalize them (and at the same time check if it was successful)
If InitializeGlobalVariables = False Then
'the function returns FALSE if the initialization process failed so we need to cancel this procedure or we use not initilized variables!
MsgBox "Variables were not intitialized. Trying to initialize them failed too. I cannot proceed."
Exit Sub
End If
End If
Debug.Print StartYear
Debug.Print BaseYear
End Sub
关于excel - 如何在 VBA 中设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57034115/