如何循环浏览许多工作表

时间:2017-11-08 23:18:50

标签: excel vba

我有以下代码。

Sub Journal()
    Dim ColL As Range, ColC  As Range
    Dim ws120 As Worksheet: Set ws120 = ThisWorkbook.Sheets("120")
    Dim ws121 As Worksheet: Set ws121 = ThisWorkbook.Sheets("121")
    Dim ws122 As Worksheet: Set ws122 = ThisWorkbook.Sheets("122")
    Dim ws123 As Worksheet: Set ws123 = ThisWorkbook.Sheets("123")
    Dim ws124 As Worksheet: Set ws124 = ThisWorkbook.Sheets("124")
    Dim ws125 As Worksheet: Set ws125 = ThisWorkbook.Sheets("125")
    Dim ws126 As Worksheet: Set ws126 = ThisWorkbook.Sheets("126")
    Dim ws127 As Worksheet: Set ws127 = ThisWorkbook.Sheets("127")
    Dim ws128 As Worksheet: Set ws128 = ThisWorkbook.Sheets("128")
    Dim ws220 As Worksheet: Set ws220 = ThisWorkbook.Sheets("220")
    Dim ws221 As Worksheet: Set ws221 = ThisWorkbook.Sheets("221")
    Dim ws402 As Worksheet: Set ws402 = ThisWorkbook.Sheets("402")
    Dim ws403 As Worksheet: Set ws403 = ThisWorkbook.Sheets("403")
    Dim wsLoc As Worksheet: Set wsLoc = ThisWorkbook.Sheets("Locker JE")
    Dim wsCof As Worksheet: Set wsCof = ThisWorkbook.Sheets("Coffee JE")
    Dim Eval, rw As Range
    Dim i As Long '<< use long in place on Integer

    With wsLoc
        Set ColL = .Cells(4, "O")
    End With
    With wsCof
        Set ColC = .Cells(4, "O")
    End With

    For i = 4 To 41
        Set rw = ws120.Rows(i)
        Temp = rw.Cells(31).Value
        Select Case rw.Cells(31).Value
            Case ""
            Case Else
                CopyLocker rw, ColL
        End Select
    Next i
End Sub

我想在每个定义的工作表的for next循环中做同样的事情。这可能是某种变量吗?

1 个答案:

答案 0 :(得分:2)

不是将所有这些声明为工作表,而是将它们加载到数组中,然后遍历数组。

这不完全是你的宏,但它显示了如何使用数组循环来完成你正在寻找的东西:

Sub Journal()
Dim wsArray() As Variant
Dim k As Long, i As Long
Dim rw As Range, ColL As Range
Dim TempCel As Range
Dim wsLoc   As Worksheet: Set wsLoc = ThisWorkbook.Sheets("Locker JE")
Dim wsCof   As Worksheet: Set wsCof = ThisWorkbook.Sheets("Coffee JE")

wsArray = Array("120", "121", "122", "123", "124", "125", "126", "127", "128", "220", "221", "402", "403", "Locker JE", "Coffee JE")
Set ColL = wsLoc.Cells(4, "O")
Set ColC = wsCof.Cells(4, "O")

For k = LBound(wsArray) To UBound(wsArray)
    With ThisWorkbook.Worksheets(wsArray(k))
        ' Do things with the worksheet.
        For i = 4 To 41
            Set rw = .Rows(i)
            Set TempCel = rw.Cells(31)
            Select Case TempCel.Value
                Case ""
                     ' Do something...
                Case Else
                    CopyLocker rw, ColL
            End Select
        Next i
    End With
Next k
End Sub

注意:这一切都假设您在希望运行此工作簿的工作簿中有其他工作表。否则,您可以执行For each ws in ActiveWorkbook.Worksheets并跳过整个数组。