是否可以在 vba 中声明一个公共变量并分配一个默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5897832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:27:24  来源:igfitidea点击:

Is it possible to declare a public variable in vba and assign a default value?

vbavariablesdefault-valuepublicvariable-declaration

提问by David

I want to do this but it won't compile:

我想这样做,但它不会编译:

Public MyVariable as Integer = 123

What's the best way of achieving this?

实现这一目标的最佳方法是什么?

回答by ray

.NET has spoiled us :) Your declaration is not valid for VBA.

.NET 宠坏了我们 :) 您的声明对 VBA 无效。

Only constants can be given a value upon application load. You declare them like so:

在应用程序加载时只能给常量赋值。你像这样声明它们:

Public Const APOSTROPHE_KEYCODE = 222

Here's a sample declaration from one of my vba projects:

这是我的一个 vba 项目中的示例声明:

VBA Constant Image

VBA 常量图像

If you're looking for something where you declare a public variable and then want to initialize its value, you need to create a Workbook_Open sub and do your initialization there. Example:

如果您正在寻找声明公共变量然后想要初始化其值的东西,您需要创建一个 Workbook_Open 子并在那里进行初始化。例子:

Private Sub Workbook_Open()
  Dim iAnswer As Integer

  InitializeListSheetDataColumns_S
  HideAllMonths_S

  If sheetSetupInfo.Range("D6").Value = "Enter Facility Name" Then
    iAnswer = MsgBox("It appears you have not yet set up this workbook.  Would you like to do so now?", vbYesNo)
    If iAnswer = vbYes Then
      sheetSetupInfo.Activate
      sheetSetupInfo.Range("D6").Select
      Exit Sub
    End If
  End If

  Application.Calculation = xlCalculationAutomatic
  sheetGeneralInfo.Activate
  Load frmInfoSheet
  frmInfoSheet.Show


End Sub

Make sure you declare the sub in the Workbook Object itself: enter image description here

确保在工作簿对象本身中声明子: 在此处输入图片说明

回答by Alain

Just to offer you a different angle -

只为给你一个不同的角度——

I find it's not a good idea to maintain public variables between function calls. Any variables you need to use should be stored in Subs and Functions and passed as parameters. Once the code is done running, you shouldn't expect the VBA Project to maintain the values of any variables.

我发现在函数调用之间维护公共变量不是一个好主意。您需要使用的任何变量都应存储在 Subs 和 Functions 中并作为参数传递。代码运行完成后,您不应期望 VBA 项目维护任何变量的值。

The reason for this is that there is just a huge slew of things that can inadvertently reset the VBA Project while using the workbook. When this happens, any public variables get reset to 0.

这样做的原因是,在使用工作簿时,有很多事情可能会无意中重置 VBA 项目。发生这种情况时,任何公共变量都会重置为 0。

If you need a value to be stored outside of your subs and functions, I highly recommend using a hidden worksheet with named ranges for any information that needs to persist.

如果您需要将值存储在 subs 和函数之外,我强烈建议使用带有命名范围的隐藏工作表来存储需要保留的任何信息。

回答by Alex K.

Sure you know, but if its a constant then const MyVariable as Integer = 123otherwise your out of luck; the variable must be assigned an initial value elsewhere.

当然你知道,但如果它是一个常数,const MyVariable as Integer = 123否则你就不走运了;必须在其他地方为变量分配一个初始值。

You could:

你可以:

public property get myIntegerThing() as integer
    myIntegerThing= 123
end property

In a Class module then globally create it;

在 Class 模块中然后全局创建它;

public cMyStuff as new MyStuffClass

So cMyStuff.myIntegerThingis available immediately.

所以cMyStuff.myIntegerThing可以立即使用。

回答by Achilles

This is what I do when I need Initialized Global Constants:
1. Add a module called Globals
2. Add Properties like this into the Globalsmodule:

当我需要初始化全局常量时,这就是我所做的:
1. 添加一个名为Globals
2. 将这样的属性添加到Globals模块中:

Property Get PSIStartRow() As Integer  
    PSIStartRow = Sheets("FOB Prices").Range("F1").Value  
End Property  
Property Get PSIStartCell() As String  
    PSIStartCell = "B" & PSIStartRow  
End Property

回答by Mohamed YOUNES

As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.

如上所述,要声明全局可访问变量,您可以在以 public 关键字开头的函数之外进行。

And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements

并且,由于在程序之外不允许做作,例如,您可以创建一个名为 InitGlobals 的子程序来初始化您的公共变量,然后您只需在语句的开头调用此子程序

Here is an example of it:

这是一个例子:

Public Coordinates(3) as Double
Public Heat as double
Public Weight as double

Sub InitGlobals()
    Coordinates(1)=10.5
    Coordinates(2)=22.54
    Coordinates(3)=-100.5
    Heat=25.5
    Weight=70
End Sub

Sub MyWorkSGoesHere()
    Call InitGlobals
    'Now you can do your work using your global variables initialized as you wanted them to be.
End Sub

回答by Duncan Howe

You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.

您可以在 General Declarations 中定义变量,然后在您的环境中触发的第一个事件中初始化它。

Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method

或者,您可以为自己创建一个具有相关属性的类并在 Initialise 方法中初始化它们

回答by Lucas B.

It's been quite a while, but this may satisfy you :

已经有一段时间了,但这可能会让您满意:

Public MyVariable as Integer: MyVariable = 123

It's a bit ugly since you have to retype the variable name, but it's on one line.

这有点难看,因为您必须重新键入变量名,但它在一行上。

回答by Paddy

It's been a while, but I believe it's going to be:

已经有一段时间了,但我相信它将是:

Public MyVariable as Integer
MyVariable = 123