【问题标题】:Declare Public Variablen and assign values - VBA声明公共变量并赋值 - VBA
【发布时间】:2020-01-08 09:19:06
【问题描述】:

有没有办法声明一个公共变量并赋值?

这是一个完美运行的子代码:

Option Explicit

Sub test()


    Dim arrStatistics As Variant

    'Set arrStatistics
    arrStatistics = Array("H/T - Goal Scored", "H/T - Goal Conceded", "H/T - Both teams Scored", "H/T - Over 0.5", "H/T - Over 1.5", "H/T - Over 2.5", "H/T - Result" _
                , "F/T - Goal Scored", "F/T - Goal Conceded", "F/T - Both teams Scored", "F/T - Over 0.5", "F/T - Over 1.5", "F/T - Over 2.5", "F/T - Result")

End Sub

这是将变量声明为Public 的方式:

Public arrStatistics As Variant

但是当我使用这个时我收到一个错误:

Public arrStatistics As Variant

'Set arrStatistics
arrStatistics = Array("H/T - Goal Scored", "H/T - Goal Conceded", "H/T - Both teams Scored", "H/T - Over 0.5", "H/T - Over 1.5", "H/T - Over 2.5", "H/T - Result" _
                , "F/T - Goal Scored", "F/T - Goal Conceded", "F/T - Both teams Scored", "F/T - Over 0.5", "F/T - Over 1.5", "F/T - Over 2.5", "F/T - Result")

【问题讨论】:

  • 对于一个不改变非数组值(即恒定相同的值) ,您也可以使用Const,例如:Public Const SomeText As String = "This is a Constant!"。但是,重申一下,这不适用于数组。

标签: excel vba variables public


【解决方案1】:

不,你必须在过程之外声明你的变量 public

Option Explicit

Public arrStatistics As Variant

然后用程序初始化内容。

Public Sub InitPublicVariabels()

    arrStatistics = Array("H/T - Goal Scored", "H/T - Goal Conceded", "H/T - Both teams Scored", "H/T - Over 0.5", "H/T - Over 1.5", "H/T - Over 2.5", "H/T - Result" _
            , "F/T - Goal Scored", "F/T - Goal Conceded", "F/T - Both teams Scored", "F/T - Over 0.5", "F/T - Over 1.5", "F/T - Over 2.5", "F/T - Result")

End Sub

但是,与其在代码中包含大量数据,不如将数据放入隐藏的工作表中,您可以轻松地将其读入数组。编辑数据更方便,代码和数据分离的好习惯。

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2018-02-02
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多