Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

vba - Delete cells in an Excel column when rows = 0

I am trying to delete all cells =0 in a column in my spreadsheet and "summon" the values which don't to the top of the column.

I am currently using

Dim row_index As Integer
Dim col_index As Integer

row_index = 7
col_index = 16

Application.ScreenUpdating = False 'turns off screen updates

While Cells(row_index, col_index) <> ""
    If Cells(row_index, col_index) = 0 Then
        Cells(row_index, col_index).Delete
    Else
        row_index = row_index + 1
    End If
Wend

Application.ScreenUpdating = True 'turns screen updates back on

But even with screen updating off it is very slow as the datasets are between 500-3500 points. Is there a better way to do this or any other tips to speed it up?

Thanks

Edit: there are a few solutions on the web but they all seem to involve blanking cells or deleting rows. I only want to delete cells and then shift cells up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Deleting cells in a loop can really be very slow. What you could do is identify the cells that you want to delete in a loop and then delete them in one go after the loop. Try this.

Option Explicit

Sub Sample()
    Dim row_index As Long, lRow As Long, i As Long
    Dim ws As Worksheet
    Dim delRange As Range

    '~~> Change this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    row_index = 7

    Application.ScreenUpdating = False

    With ws
        lRow = .Range("P" & .Rows.Count).End(xlUp).Row

        For i = row_index To lRow
            If .Range("P" & i).Value <> "" And .Range("P" & i).Value = 0 Then
                If delRange Is Nothing Then
                    Set delRange = .Range("P" & i)
                Else
                    Set delRange = Union(delRange, .Range("P" & i))
                End If
            End If
        Next
    End With

    If Not delRange Is Nothing Then delRange.Delete shift:=xlUp
    Application.ScreenUpdating = True
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...