通过公式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 

如果找不到子string,或者如果find子string的索引 ,则应该使用Instr返回0。

当你循环行删除,你应该从底部到顶部使用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 

要快速处理每个工作表并删除G列中不包含连字符的行, AutoFilter方法可能效果最佳。

 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