Excel VBA:如果列A包含string中的数字,则删除行

我试图在Excel中编写一个公式以删除整个行,如果列C中的单元格包含数字中的一个数字,数字0 除外

例如

A2 - delete A0 - don't delete M - don't delete ABC6 - delete NN - don't delete Sub FindInvalid() Dim Firstrow As Long Dim Lastrow As Long Dim Lrow As Long Dim CalcMode As Long Dim ViewMode As Long Dim JEType As Variant InvalidCharacters= Array(1, 2, 3, 4, 5, 6, 7, 8, 9) With Application CalcMode = .Calculation .Calculation = xlCalculationManual .ScreenUpdating = False End With With ActiveSheet .Select ViewMode = ActiveWindow.View ActiveWindow.View = xlNormalView .DisplayPageBreaks = False Firstrow = .UsedRange.Cells(1).Row Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row For Lrow = Lastrow To Firstrow Step -1 With .Cells(Lrow, "C") If Not IsError(.Value) Then Debug.Print (.Value) If IsInArray(.Value, InvalidCharacters) = True Then .EntireRow.Delete 'This will delete each row where Column C contains a number End If End With Next Lrow End With ActiveWindow.View = ViewMode With Application .ScreenUpdating = True .Calculation = CalcMode End With End Sub 

以上的作品很好,但我正在努力与下面。

 Function IsInArray(StringToBeFound As String, arr As Variant) As Boolean IsInArray = Not IsError(Application.Find(StringToBeFound, "contains", arr, 0)) End Function 

任何帮助将不胜感激。

您一次只检查一个单元格,看是否包含某些数字。

而不是IsInArray函数,也许:

  With .Cells(Lrow, "C") If Not IsError(.Value) Then Debug.Print (.Value) If .Value Like "*[1-9]*" Then .EntireRow.Delete 'This will delete each row where Column C contains a number End If End With 

编辑:对于大型工作表,这可能不是最有效的方法。 一种可能性是使用高级filter。

对于高级筛选,您可以使用以下条件的公式:

  =NOT(OR(ISNUMBER(FIND({1,2,3,4,5,6,7,8,9},C9)))) 

您可能想要将结果复制到另一个位置。

一个VBA例程,可能工作更快:

algorithm

  • 将列C读入一个variables数组
  • 处理每个项目,看它是否符合要删除的标准
  • Collect每个要删除项目的行号
  • 使用Union方法创build要删除的范围
  • 删除范围

 Option Explicit Sub delNumRows() Dim V As Variant Dim COL As Collection Dim I As Long Dim R As Range V = Range(Cells(1, 3), Cells(Rows.Count, 3).End(xlUp)) Set COL = New Collection For I = 1 To UBound(V) If V(I, 1) Like "*[1-9]*" Then COL.Add I Next I For Each V In COL If R Is Nothing Then Set R = Cells(V, 1).EntireRow Else Set R = Union(R, Cells(V, 1).EntireRow) End If Next V R.Delete End Sub 

站在arrays的“structrure”被search,你可以使用这个:

 Function IsInArray(StringToBeFound As String, arr As Variant) As Boolean IsInArray = InStr("|" & Join(arr, "|") & "|", "|" & StringToBeFound & "|") > 0 End Function