Search code examples
vbadeclare

VBA: declaring/setting global and permanent variable objects and accessing in other Subs/Functions


I want to declare variable/objects that should be:

  • Global: I will be able to use them in all Subs/Functions
  • Permanent: some events trigger those subs and the variable should still be accessible/available to the subs.

The use of Workbook_Open() sub is not required, but it was the closest thing I found to a constructor... My simplified structure:

In ThisWorkbook:

Public HS As Worksheet <-- the global variable

Private Sub WorkbookOpen()
  Set HS = ActiveWorkbook.Sheets(1) 
End Sub

In Module1 :

Sub HistCheck()
  HS.Activate <-- Objet required
End Sub

Solution

  • You need to place your global variables within a module, not the workbook or sheet*.

    In Modeul1:

    Global Public HS As Worksheet
    

    Only Modules can declare variables that can be used throughout the worksheet objects, subs, and functions.

    You were correct in placing this code under the workbook object

    Under Workbook:

    Private Sub WorkbookOpen()
      Set HS = ActiveWorkbook.Sheets(1) 
    End Sub
    

    With both of these items in the proper locations, you can place your code as follows in any location of the document, as long as the document is loaded in memory of course.

    Sub HistCheck()
      HS.Activate
    End Sub
    

    If you have any issues, please write back what the exact error messages are to allow troubleshooting.