2016-11-28 160 views
0

我想學習一點VBA。所以我是新手。VBA-Excel循環刪除表格的最後一行

我想要一個從第二張到最後一張的循環,然後刪除表格中單個表格的最後一行。

目前我有這個代碼,我在網上搜索。

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 

可有人告訴我,我做錯了嗎? 非常感謝

+0

你得到了什麼錯誤? – user3598756

回答

4

最大的可能是你的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 
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