vba 工作表变量数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21513026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:41:54  来源:igfitidea点击:

Array of worksheet variable

arraysexcelvbaexcel-vba

提问by abdfahim

As per documentation, I can define array of worksheets like below

根据文档,我可以定义如下所示的工作表数组

Dim sheetsArray As Sheets
Set sheetsArray = ActiveWorkbook.Sheets(Array("Sheet1", "Sheet2"))

But what happens if my worksheets are dynamically created and pointed by pointer variable like below? How can I make an array of them so that I can loop through them to do same activity?

但是,如果我的工作表是动态创建的并由如下所示的指针变量指向,会发生什么?如何制作它们的数组,以便我可以遍历它们以执行相同的活动?

Dim tempsheet1 As Worksheet
Dim tempsheet2 As Worksheet

Set tempsheet1 = Sheets.Add
Set tempsheet2 = Sheets.Add

Dim sheetsArray As Sheets
Set sheetsArray = ActiveWorkbook.Sheets(Array(tempsheet1, tempsheet2)) ' Doesn't work
For Each msheets In sheetsArray
    With msheets
        DO SOMETHING
    End With
Next msheets

回答by Dmitry Pavliv

Since you should specify sheet names in Array, change

由于您应该在 Array 中指定工作表名称,因此更改

Set sheetsArray = ActiveWorkbook.Sheets(Array(tempsheet1, tempsheet2))

to

Set sheetsArray = ActiveWorkbook.Sheets(Array(tempsheet1.Name, tempsheet2.Name))