簡體   English   中英

Vba-Excel循環刪除表的最后一行

[英]Vba-Excel loop delete last row of a table

我正在嘗試學習一些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

有人可以告訴我我在做什么錯嗎? 非常感謝

您的ActiveWorkbook最有可能少於7工作表

所以只要改變

WS_Count = 7

WS_Count = ActiveWorkbook.Worksheets.Count

此外,您可以避免Select / Selection而使用完整的Range參考,如下所示:

Option Explicit

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

    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = ActiveWorkbook.Worksheets.Count

    ' Begin the loop.
    For I = 2 To WS_Count

        ' deletes the last line of current worksheet
        Worksheets(I).Cells(Rows.Count, 1).End(xlUp).EntireRow.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

這是另一種使用For Each ws In Worksheets中的工作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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM