循环公式 Excel VBA

Loop through formula Excel VBA

我需要遍历现有公式并删除整行(如果其中没有减号)。有没有办法一个字符一个字符地遍历公式,或者有另一种方法来识别公式中是否有“-”?

Sub clearvalidation()
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Sheets
    Set vali = ws.Cells.Find("Validation", LookIn:=xlValues, LookAt:=xlPart)
    If Not vali Is Nothing Then
        fr = vali.Row + 2
        lr = ws.Cells(fr + 1, 6).End(xlDown).Row
        For exclrow = fr To lr
            For Each char In ws.Cells(exclrow, 7)
                If char = "-" Then
                    check = "ok"
                    Exit For
                End If
            Next char
            If check <> ok Then check = "delete"
            Select Case check
                Case Is = "ok"
                    Stop
                Case Is = "delete"
                    Stop
            End Select
        Next exclrow
    End If
    vali = Empty
Next ws

End Sub

要快速浏览每个工作表并删除 G 列中不包含连字符的行,AutoFilter Method 可能效果最好。

Sub Macro1()
     Dim w As Long

     For w = 1 To Worksheets.Count
        With Worksheets(w)
            If .AutoFilterMode Then .AutoFilter = False
            With .Cells(1, 1).CurrentRegion
                .AutoFilter Field:=7, Criteria1:="<>*-*"
                With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                    If Application.Subtotal(103, .Cells) Then
                        .Cells.EntireRow.Delete
                    End If
                End With
            End With
        End With
     Next w

End Sub

您应该使用 Instr,如果找不到您要查找的子字符串,则 return 为 0;如果找到,则为该子字符串的 index找到了。

并且当你循环删除行时,你应该使用Step -1从下到上以避免丢失一些行(如果第i行被删除,第i+1行将成为新行我和你会在下一个之后错过它)。

Sub clearvalidation()
Dim ws As Worksheet, _
    FirstAddress As String, _
    cF As Range


For Each ws In ActiveWorkbook.Sheets
    ws.Range("A1").Activate
    With ws.Cells
        Set vali = .Find("Validation", LookIn:=xlValues, LookAt:=xlPart)
        If Not vali Is Nothing Then
            FirstAddress = vali.Address
            'If there is a result, keep looking with FindNext method
            Do
                fr = vali.Row + 2
                lr = ws.Cells(fr + 1, 6).End(xlDown).Row
                For exclrow = lr To fr Step -1
                    If InStr(1, ws.Cells(exclrow, 7).Formula, "-") Then
                        ws.Cells(exclrow, 7).EntireRow.Delete shift:=xlUp
                    Else
                    End If
                Next exclrow
                Set vali = .FindNext(vali)
            'Look until you find again the first result
            Loop While Not vali Is Nothing And vali.Address <> FirstAddress
        End If
        vali = Empty
    End With
Next ws


End Sub