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

时间:2017-01-28 19:50:49

标签: excel vba excel-vba

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

e.g。

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:6)

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

可能代替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

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

对于高级过滤器,您可以使用条件的公式:

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

您可能希望将结果复制到其他位置。

可能更快运行的VBA例程:

算法

  • 将C列读入变量数组
  • 处理每个项目以查看其是否符合要删除的条件
  • Collect要删除的每个项目的行号
  • 使用Union方法创建要删除的范围
  • 删除范围
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

答案 1 :(得分:0)

站在要搜索的阵列的“结构”中,你可以使用它:

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