我想根据工作表名称执行特定的任务。为了遍历所有这些工作表,我通常定义一个字符串数组,然后像这样遍历该数组:
Option Explicit
dim i as integer
dim arr_test as variant
dim wb as workbook
dim ws as worksheet
arr_test = Array("Test1", "Test2", "Test3")
set wb = application.activeworkbook
for i = 0 to 2
set ws = wb.sheets(arr_test(i))
'do something
next i
我的问题是,有更好的方法吗? (即使用更少的行并提高处理速度的计算机。)
谢谢!
答案 0 :(得分:2)
Dim ws as worksheet
For each ws in ActiveWorkbook.Worksheets
Select case ws.name
Case "Test1", "Test2", "Test3"
'do something to ws
End Select
next ws
如果您想对所有工作表进行处理,则可以省略选择的情况,它甚至更快
答案 1 :(得分:1)
回答您的问题,没有一种主要的方法可以改进您的代码。我会同意第一个答案的方法,方法是循环浏览工作表以匹配三个名称,因为这样做可以防止大写问题,例如:UCASE("TEST1") = UCASE(ws.name)
这是您的代码稍微干净一点的版本,其行数更少。它也是动态的,因此,如果添加另一个测试,则无需更改循环的代码行,因为它使用了Ubound
选项。
Dim i As Long, arr_test() As Variant, wb As Workbook, ws As Worksheet
arr_test = Array("Test1", "Test2", "Test3")
Set wb = Application.ActiveWorkbook
For i = 0 To UBound(arr_test)
Set ws = wb.Sheets(arr_test(i))
'do something
Next i