是否可以在vba中声明公共变量并分配默认值? [英] Is it possible to declare a public variable in vba and assign a default value?

查看:435
本文介绍了是否可以在vba中声明公共变量并分配默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Public MyVariable as Integer = 123

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

What's the best way of achieving this?

推荐答案

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

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

在应用程序中只能给常量一个值加载。您可以这样声明它们:

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

Public Const APOSTROPHE_KEYCODE = 222

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

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

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

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:

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

确保在Workbook对象本身中声明了子:

Make sure you declare the sub in the Workbook Object itself:

这篇关于是否可以在vba中声明公共变量并分配默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆