循环遍历表单

时间:2014-05-11 02:26:23

标签: vba loops excel-vba excel

我试图遍历一个(随机命名的)工作表列表,并为每个工作表计算最后一行,然后遍历所有行并执行一些代码。

我已尝试过以下代码,但我得到了Invalid Procedure Call or Argument。我已经以各种方式进行了修改,但它让我发疯了......先谢谢你。

Sub myloop()

    Dim ws As Variant
    Dim WsArray As Variant
    Dim rcount As Integer


WsArray = Array("mysheet1", "mysheet2", "mysheet3", "mysheet4")

With ThisWorkbook

    For Each ws In WsArray

        rcount = .Worksheets(ws).Cells("A1").End(xlDown).Row

        For i = 1 To rcount

            If ...Then

            End If
        Next

    Next

End With

End Sub

2 个答案:

答案 0 :(得分:1)

@Santosh对寻找最后一行提出了一个很好的观点。至于原始问题,在任何Workbook中都存在Worksheets集合,根据您的结构,实际上可能更容易循环:

Dim ws As Worksheet
For Each ws In Worksheets
    'match worksheet names if necessary using ws.Name...
    '
    'do other cool stuff...
    '
    'wrap it all up
Next ws

答案 1 :(得分:0)

试试这个。而不是去单元格A1并找到最后一行,最好去最后一个单元格(rows.count),然后再上去。

Sub myloop()

    Dim ws As Variant
    Dim WsArray As Variant
    Dim rcount As Integer


    WsArray = Array("mysheet1", "mysheet2", "mysheet3", "mysheet4")

    With ThisWorkbook

        For Each ws In WsArray

           With .Worksheets(ws)
             rcount = .Cells(.Rows.Count, "A").End(xlUp).Row
            End With

            For i = 1 To rcount

                'If .. Then


                End If
            Next

        Next

    End With

End Sub