清除一列值中的单元格,如果它有string的话

我试图写/find一个macros运行时删除单元格中的值,如果列中的单元格不是一个数字。 IE删除列B中的所有单元格,如果find一个string。 我有这个脚本删除空行。 只是试图重新编写它,以便它可以删除基于这些条件的行

Sub RemoveRows() Dim lastrow As Long Dim ISEmpty As Long lastrow = Application.CountA(Range("A:XFD")) Range("A1").Select Do While ActiveCell.Row < lastrow ISEmpty = Application.CountA(ActiveCell.EntireRow) If ISEmpty = 0 Then ActiveCell.EntireRow.Delete Else ActiveCell.Offset(1, 0).Select End If Loop End Sub 

该代码从列B中的最后一个单元格向后迭代,并使用IsNumeric()函数检查单元格中的值是否为数字。

如果该值不是数字,则会删除整行。

注意:当使用循环时,向后循环(即从最后一行到第一个循环)是必要的,因为每当行被删除时索引都会被移位。 因此,为了避免跳过一些行,需要迭代。

 Sub KeepOnlyNumbers() Application.ScreenUpdating = False Dim ws As Worksheet Set ws = Sheets("Sheet1") Dim i As Long ' iterating backwards (from last row to first to keep the logic flow) For i = ws.Range("B" & ws.Rows.Count).End(xlUp).Row To 1 Step -1 ' check whether the value is numeric If Not IsNumeric(Range("B" & i)) Then ' if not numeric then clear the cells content Range("B" & i).ClearContents End If Next i Application.ScreenUpdating = True End Sub 

您可以使用IsNumeric来评估一个对象是否可以被评估为一个数字。 所以你可以添加:

 If Not IsNumeric(ActiveCell) Then ActiveCell.EntireRow.Delete Else ActiveCell.Offset(1, 0).Select End If 

到你的Do While循环,它应该做你想要的。 我没有testing过这个; 让我知道,如果你得到一个错误。

即使在删除行时,也不必向后迭代,可以在联合范围内执行联合并调用delete / clear。

 Sub UnionOnCondition() Dim usedColumnB Set usedColumnB = Intersect(ActiveSheet.UsedRange, _ ActiveSheet.Columns("b")) If usedColumnB Is Nothing Then _ Exit Sub Dim result: Set result = Nothing Dim cellObject For Each cellObject In usedColumnB ' skip blanks, formulas, dates, numbers If cellObject = "" Or _ cellObject.HasFormula Or _ IsDate(cellObject) Or _ IsNumeric(cellObject) Then GoTo continue If result Is Nothing Then Set result = cellObject.EntireRow Else Set result = Union(result, cellObject.EntireRow) End If continue: Next If Not result Is Nothing Then _ result.Select ' result.Clear or result.Delete End Sub