简体   繁体   中英

How to correctly Public and Set a Worksheet?

Public sp As Worksheet  //  on top of ThisWorkbook module
...
Sub one()
Set sp = Sheets("blueSky")  // marked
MsgBox sp.Name
...
Sub two()
Set sp = Sheets("blueSky")  //  marked
MsgBox sp.Range("A1").Value

Marked line is allways the same.
So, is it possible to write the marked line only once - and where ?
I tried on Workbook.Open event - without result
I want in each Sub write only the third line - which is allways different.

If you put the followin in a module (not ThisWorkbook ) you get a global Worksheet variable:

Option Explicit

Global sp As Worksheet

You can then adress it in any of the following ways in ThisWorkbook (subs one() and two() will also work in a module):

Option Explicit

Public Sub one()
    Set sp = Sheets("Sheet1")  '// marked
    MsgBox sp.Name
End Sub

Sub two()
    Set sp = Sheets("Sheet2") ' //  marked
    MsgBox sp.Range("A1").Value
End Sub

Private Sub Workbook_Open()
    Set sp = Sheets("Sheet3")
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM