有多个工作表的声明?

时间:2015-08-13 19:16:38

标签: excel excel-vba vba

我正在为

目前的工作簿中的某些工作表重复一组操作
For Each ws In Worksheets
    Select Case ws.Name
        Case "2015", "2016", "Rate", "Month"
        'code here
    End Select
Next ws

这似乎非常低效的XD 是否可以做类似

的事情
With ws1, ws2, ws3
'code here
end with

我没有那么多张,所以循环只需要约2秒但是必须有更快/更优雅的方式?

1 个答案:

答案 0 :(得分:2)

工作表是一个包含当前工作簿中所有工作表的集合。

为简化代码,您可以只使用要处理的工作表创建自己的集合,然后使用它。那么你就不需要select case语句来限制循环处理哪些工作表。

但是,查看集合可能比按照您的方式执行更多工作。虽然这不是OO的方式。

所以在一个模块中你可能会做这样的事情:

Sub aa()
    Dim colSheets As Collection
    Set colSheets = New Collection

    colSheets.Add Sheet1  ' here I use the object name from the VBA "(Name)" property
    colSheets.Add Worksheets("MyWorksheetName")
    colSheets.Add Worksheets("SummarySheet")

    Dim sht As Worksheet
    For Each sht In colSheets
        Debug.Print sht.Name
    Next sht

    Set colSheets = Nothing
End Sub
相关问题