Excel VBA - Scan range and delete empty rows [duplicate]

这一生的挚爱 提交于 2020-01-05 07:25:27

问题


I have a spreadsheet that populates rows based on data from a pivot table (imported through ODBC). I'm using VLOOKUP, for example:

=VLOOKUP(A8;Data!B1:I298;2;FALSE)

The result is something like

Name1
Name2
Address1
Address2
Postalcode
Country

It might happen that some of the pivot columns are empty, resulting in

Name1
0
Address1
0
Postalcode
0

What I need is some sort of function that loops through a range of rows, for example A8 - A14 and delete the rows that are "empty". My problem is that the rows are not truly empty, they still return 0 and contain the VLOOKUP formula.

Is this achievable somehow? I hope I'm making sense.

Thanks.


回答1:


Example

with the code

Sub Delete0s()
    Dim i As Long
    For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
        If Range("A" & i) = 0 Then
            Range("A" & i).Delete shift:=xlUp
        End If
    Next i
End Sub

deletes 0s so the result


achieve the same result using autofilter which is normally a bit faster than looping

code

Sub Delete0s()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")
    lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

    Set rng = ws.Range("A1:A" & lastRow)
    With rng
        .AutoFilter Field:=1, Criteria1:="=0"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ws.AutoFilterMode = False
End Sub

result



来源:https://stackoverflow.com/questions/19537487/excel-vba-scan-range-and-delete-empty-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!