循环宏在Step step上工作但在自动运行时失败

时间:2017-10-01 13:14:21

标签: excel vba excel-vba for-loop autofilter

我在理论上创建一个宏来将字符串存储为变量,然后使用多个循环自动过滤每个工作表中的每一列,并删除其中包含字符串的所有行。

当点击F8逐步执行宏时,一切似乎都能正常工作,直到宏结束。但是,只要我尝试按下运行按钮,它就会在我选择了初始单元格的选项卡上运行,我想通过宏来放置它。

运行Excel 2016,如果这有任何区别。

Sub Delete_Selection()

Dim Selection As Range
Dim Search As String
Dim ColumnCount As Long
Dim WS As Worksheet
Dim J As Integer

Set Selection = ActiveCell
Search = Selection

For i = 1 To Sheets.Count
    With Sheets(i)
        .AutoFilterMode = False
        Set WS = ActiveSheet
        ColumnCount = WS.Cells(2, WS.Columns.Count).End(xlToLeft).Column

        With .Range("A1").CurrentRegion
            For J = 1 To ColumnCount
                On Error Resume Next
                .AutoFilter J, Search
                .Offset(1).SpecialCells(12).EntireRow.Delete
                ActiveSheet.ShowAllData

                On Error GoTo 0
            Next J
        End With
        .AutoFilterMode = False

    End With
Next i

End Sub

干杯,

1 个答案:

答案 0 :(得分:1)

似乎您想要选择一个带有值的单元格,然后循环遍历所有工作表,删除任何列中具有该值的行。

Option Explicit

Sub Delete_Selection()

    Dim srch As String
    Dim i As Long, j As Long

    srch = ActiveCell.Value2

    For i = 1 To Worksheets.Count
        With Worksheets(i)
            If .AutoFilterMode Then .AutoFilterMode = False
            With .Range("A1").CurrentRegion
                For j = 1 To .Columns.Count
                    .AutoFilter field:=j, Criteria1:=srch
                    With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                        If CBool(Application.Subtotal(103, .Cells)) Then
                            .EntireRow.Delete
                        End If
                    End With
                    .AutoFilter field:=j
                Next j
            End With
            .AutoFilterMode = False
        End With
    Next i

End Sub