Vba-Excel循环删除表的最后一行

时间:2016-11-28 12:01:40

标签: excel vba excel-vba

我正在尝试学习一点VBA。所以我是新手。

我想要一个从第二张到最后一张的循环,然后在单张的一张表中删除一张表的最后一行。

目前,我在网上搜索此代码。

 Sub ApagaLoop()
'Apaga todas as linhas das tabelas, e percorre todas as folhas.
    Dim WS_Count As Integer
    Dim I As Integer
    Dim sht As Worksheet
    Dim LastRow As Long


    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = 7

    ' Begin the loop.
    For I = 2 To WS_Count

        ' Insert your code here.
        Sheets(I).Cells(Rows.Count, 1).End(xlUp).Rows().Select
        Rows(ActiveCell.Row).Select
        Selection.Delete Shift:=xlUp

        ' The following line shows how to reference a sheet within
        ' the loop by displaying the worksheet name in a dialog box.
        MsgBox ActiveWorkbook.Worksheets(I).Name

    Next I

End Sub

我收到错误:

Sheets(I).Cells(Rows.Count, 1).End(xlUp).Row

有人可以告诉我我做错了什么吗? 非常感谢

2 个答案:

答案 0 :(得分:4)

您的/css/vendor.min.333311133.css很可能少于 location ~* /css\/vendor\.min\.(.*)\.css { try_files $uri ~* /css\/vendor\.(.*)\.css =404; } 工作表

所以只需改变

ActiveWorkbook

7

此外,您可以避免使用WS_Count = 7 / WS_Count = ActiveWorkbook.Worksheets.Count 并使用完整的Select引用,如下所示:

Selection

答案 1 :(得分:0)

以下是使用For Each ws In Worksheets引用工作表和.Find引用工作表中最后一行的另一种方法,无论它在哪一列。

Sub ApagaLoop()
    Dim ws As Worksheet
    Dim Target As Range
    For Each ws In Worksheets
        If ws.Index <> 1 Then

            Set Target = ws.Cells.Find(What:="*", After:=ws.Range("A1"), SearchDirection:=xlPrevious)
            If Not Target Is Nothing Then
                If MsgBox("Do you want to delete " & Target.EntireRow.Address(External:=True), vbYesNo, "Delete Last Row") = vbYes Then
                    Target.EntireRow.Delete
                End If
            End If
        End If
    Next
End Sub