Can a worksheet object be declared globally in Excel VBA?

后端 未结 6 1430
余生分开走
余生分开走 2021-01-05 02:32

I\'m refactoring a number of modules in an Excel 2003 workbook and the same set of worksheets are declared in each procedure in each module; I\'d like to just declare them o

6条回答
  •  情书的邮戳
    2021-01-05 02:40

    You could, but do you really want more global variables? Why not create (within a standard module) a public property ModelWorksheet, like this:

    Public Property Get ModelWorksheet As Worksheet
        Const ModelWorksheetName As String = "gs_model"
        Set ModelWorksheet = ActiveWorkbook.Worksheets(ModelWorksheetName)
    End Property
    

    ...then your code can do:

    With ModelWorksheet
        .Cells(1,1).Value = "foo"
        .Font.Bold = True
    End With
    

    Note also that you can refer to any of the worksheets in the current workbook directly, so if there's a sheet called Sheet1 you can do:

    With Sheet1
        .Cells(1,1).Value = "foo"
        .Font.Bold = True
    End With
    

提交回复
热议问题