stu*_*tch 1 excel vba excel-vba
我试图在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
编辑: 对于大型工作表,这可能不是最有效的方法.一种可能性是使用高级过滤器.
对于高级过滤器,您可以使用条件的公式:
  =NOT(OR(ISNUMBER(FIND({1,2,3,4,5,6,7,8,9},C9))))
您可能希望将结果复制到其他位置.
可能更快运行的VBA例程:
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
| 归档时间: | 
 | 
| 查看次数: | 756 次 | 
| 最近记录: |