简体   繁体   中英

How to list all sheets in opened Workbook in Workbook_Open event handler Sub?

When user opens a saved Workbook, I want to load data from my hidden sheet in it.

I thought I would use Workbook_Open Sub and load data from that worksheet from this Sub, but then this Sub is invoked, I do not have any Workbook yet.

Here is an example:

Private Sub Workbook_Open()
   Debug.Print "Open: " & Workbooks.Count 'prints 0 to console
End Sub

I also tried this approach:

Private Sub Workbook_Open()
   Dim sh As Worksheet
   For Each sh In Sheets
      Debug.Print sh.name
      'prints only Sheet1, Sheet2, Sheet3 and do not print the name of my data sheet.
   Next sh
End Sub

So my question is: how can I get a sheet by name when user opens a Workbook?

I think that you were simply missing some references.

I've just tested this and work nicely :

Private Sub Workbook_Open()
   Debug.Print "Opened wB: " & Application.Workbooks.Count

   Dim wS As Worksheet

   Debug.Print "Sheets: "
   For Each wS In ThisWorkbook.Sheets
      Debug.Print wS.Name
   Next wS
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