如何在VBA中设置全局变量

brb*_*brb 4 excel vba

我想在一个模块中的 VBA 中定义一个全局变量,并在其他 VBA 模块中使用它。

我正在尝试遵循:如何在 VBA 中声明全局变量?

我创建了一个名为“GlobalVariables”的新模块,首先声明公共变量,然后在函数中设置它们的值(尝试在开放代码中执行此操作会导致错误)。我的代码如下。

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
Run Code Online (Sandbox Code Playgroud)

Pᴇʜ*_*Pᴇʜ 5

  1. 确保将全局变量放在模块中而不是工作表范围中,以便在其他模块中访问它。

  2. 你的Function应该是 aSub因为它不返回任何东西。

  3. 如果您的单元格例如,您的代码将会出错。包含文本(字符串)。永远不要相信用户的输入。始终验证!

所以我建议如下

模块 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
Run Code Online (Sandbox Code Playgroud)

您可以访问任何其他模块中的变量,例如:

模块2

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
Run Code Online (Sandbox Code Playgroud)