从列中删除数字

时间:2018-08-02 05:58:51

标签: vba formula

我在B列中有以下成员

4025015659
4025015660
4025015661
4025015662
-266490.78
-266491.78
-266492.78
-266493.78
0
0
0

我需要删除除负数以外的所有数字。是否可以使用公式或VBA代码。

2 个答案:

答案 0 :(得分:1)

尝试一下

Sub deleteRows()

    Dim lastRow As Long
    lastRow = Range("B" & Rows.CountLarge).End(xlUp).Row

    For i = lastRow To 1 Step -1
        If Cells(i, "B") < 0 Then
             Cells(i, "B").EntireRow.Delete
        End If
    Next
End Sub

答案 1 :(得分:1)

一次性删除并使用With语句/限定范围会更有效

Option Explicit
Public Sub deleteRows()
    Dim unionRng As Range, loopRange As Range, rng As Range
    With Worksheets("Sheet3") '>==Change to correct sheet
        Set loopRange = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row)
        For Each rng In loopRange
            If rng.Value < 0 Then
                If Not unionRng Is Nothing Then
                    Set unionRng = Union(unionRng, rng)
                Else
                    Set unionRng = rng
                End If
            End If
        Next
    End With
    If Not unionRng Is Nothing Then unionRng.EntireRow.Delete
End Sub