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

后端 未结 8 678
旧时难觅i
旧时难觅i 2020-12-09 01:33

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

Public MyVariable as Integer = 123

What\'s the best way of achieving this?

相关标签:
8条回答
  • 2020-12-09 01:57

    .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

    0 讨论(0)
  • 2020-12-09 02:05

    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.

    0 讨论(0)
提交回复
热议问题