如果 C 列中的单元格在单元格中包含一个数字(数字 0 除外),我正在尝试在 Excel 中编写一个公式来删除整行。
例如
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
关于vba - Excel VBA : Delete row if Column A contains a number within the string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914134/