声明公共变量并赋值 - VBA
Posted
技术标签:
【中文标题】声明公共变量并赋值 - VBA【英文标题】:Declare Public Variablen and assign values - 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!"
。但是,重申一下,这不适用于数组。
【参考方案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
但是,与其在代码中包含大量数据,不如将数据放入隐藏的工作表中,您可以轻松地将其读入数组。编辑数据更方便,代码和数据分离的好习惯。
【讨论】:
以上是关于声明公共变量并赋值 - VBA的主要内容,如果未能解决你的问题,请参考以下文章