循环通过范围的工作表

时间:2018-03-14 13:44:43

标签: arrays vba excel-vba loops range

我正在尝试遍历一系列工作表。但是,从工作表上的范围中选择工作表时出现错误。

Sub Calc_sheets()

Dim sheetnames As Variant
sheets("Calc_sheets").Select
'sheetnames = Worksheets("Calc_sheets").Range("a2:a4").Value # returns an error in row "Sheet = sheetnames(k)"

sheetnames = Array("Sheet1", "Sheet2") # works fine

For k = 0 To Application.CountA(sheetnames) - 1

        Sheet = sheetnames(k)
        sheets(Sheet).Select
        ActiveSheet.Calculate
Next k

End Sub

你知道如何解决这个问题吗?

最佳,

3 个答案:

答案 0 :(得分:3)

使用Lbound和Ubound循环遍历数组。

将sht声明为工作表并设置工作表。然后避免使用select和activate。

Sub Calc_sheets()

Dim sheetnames As Variant
Dim sht as Worksheet


sheetnames = Array("Sheet1", "Sheet2")

For k = LBound(sheetnames) to Ubound(sheetnames)

        Set Sht = worksheets(sheetnames(k))
        sht.Calculate
Next k

End Sub

答案 1 :(得分:3)

你必须使用Set

Dim Sheet AS Worksheet
Set Sheet = sheetnames(k)

但您可以将其缩短为

Sub Calc_sheets()
    Dim sheetnames As Variant
    sheetnames = Array("Sheet1", "Sheet2")

    Dim Sheet As Variant
    For Each Sheet In sheetnames
        Sheets(Sheet).Calculate
    Next
End Sub

甚至更短:

Sub Calc_sheets()
    Dim Sheet As Variant
    For Each Sheet In Array("Sheet1", "Sheet2")
        Sheets(Sheet).Calculate
    Next
End Sub

答案 2 :(得分:1)

Sub CalcSheets()

    Dim k           As Long
    Dim sheetnames  As Variant

    sheetnames = Array("Sheet1", "Sheet2")

    For k = 0 To Application.CountA(sheetnames) - 1
        Sheets(sheetnames(k)).Calculate
    Next k    
End Sub

一般情况下,应避免使用SelectActiveSheet,如果您明确使用.Calculate,则整个工作表设计中的内容应该是完全错误的。