对于每个工作表,删除超过一个月的数据

时间:2017-11-07 21:06:01

标签: excel vba excel-vba

嘿伙计们,所以基本上我有一大堆床单,我希望通过按下按钮,我可以在月底过滤旧数据并删除它。 (原因并不总是我可以清除第一个数据,有时用户会在我可以设置当月之前来工作簿)

所以这是已设置的代码:

Private Sub CommandButton4_Click()
Dim ws As Worksheet
Dim Rng As Range
Dim LastRow As Long, LastCol As Long



response = MsgBox("Tem a Certeza que quer Limpar todo os Dados?", vbYesNo)
If response = vbNo Then Exit Sub

For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Formularios" Then
    If ws.Name <> "Coordenador" Then
        If ws.Name <> "LookupList" Then
            With ws
                .Unprotect Password:=pass
                LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
                LastCol = .Range("A" & .Columns.Count).End(xlToLeft).Column
                Set Rng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
            End With
            With Rng
                .AutoFilter Field:=1, Criteria1:=xlFilterLastMonth
                .SpecialCells(xlCellTypeVisible).Offset(1, 0).Resize(.Rows.Count).Rows.Delete
            End With
            With ws
                .AutoFilterMode = False
                If .FilterMode = True Then
                    .ShowAllData
                End If
                .Protect Password:=pass
            End With
        End If
    End If
End If
Next
End Sub

当我运行代码时,我在行上得到错误1004对象

 .SpecialCells(xlCellTypeVisible).Offset(1, 0).Resize(.Rows.Count).Rows.Delete 

有人在我的代码上看到任何错误吗?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

这是我通常使用的形式。

        With ws
            .Unprotect Password:=pass
            LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
            LastCol = .cells(1, .Columns.Count).End(xlToLeft).Column
            Set Rng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
        End With
        With Rng
            .AutoFilter Field:=1, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic
            with .resize(.rows.count-1, .columns.count).offset(1, 0)
                if cbool(application.subtotal(103, .cells)) then
                    .SpecialCells(xlCellTypeVisible).EntireRow.Delete
                end if
            end with
        End With

答案 1 :(得分:1)

我将初始范围(rng)更改为仅第二行并取出偏移并调整大小。由于范围仅用于此子例程,为什么要调整大小? 我在本月和最后一天测试了5或6个日期,甚至将它们排除在外并且按预期工作。

sub stest()
            With Worksheets(1)

                LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
                Set Rng = .Range(.Cells(2, 1), .Cells(LastRow, 1))
            End With
            With Rng
                .AutoFilter Field:=1, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic
                .offset(1,0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
            End With
End Sub