Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Public MyVariable as Integer = 123 

What's the best way of achieving this?

like image 563
David Avatar asked May 05 '11 12:05

David


People also ask

How do you assign a public variable in VBA?

Step 1: Create a new module. Go to Insert tab, click on Module to add a new module under VBE. Step 2: Add Option Explicit within the module. Step 3: Define a new variable named var1 and var2 both as a type integer.

How do you declare and assign a value to a variable in VBA?

Setting variables In VBA, declaring variables is optional, but you can't declare AND set the variable at the same time. We've added a line that assigns the value of a variable. In VBA, just append “. Value”, an equals sign, and the value you want to assign (in quotation marks).

Where to declare public variables in Excel VBA?

Use the Public statement to declare public module-level variables. Public variables can be used in any procedures in the project. If a public variable is declared in a standard module or a class module, it can also be used in any projects that reference the project where the public variable is declared.


1 Answers

.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 

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

VBA Constant Image

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 

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

like image 156
ray Avatar answered Sep 20 '22 17:09

ray