简体   繁体   English

如何在Workbook_Open事件处理程序Sub中列出打开的工作簿中的所有工作表?

[英]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. 我以为我会使用Workbook_Open Sub并从该Sub加载该工作表中的数据,但是随后又调用了此Sub,我还没有任何Workbook。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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