Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA to delete cells in a column and shift-left based on the cell's value?

Tags:

excel

vba

How can I delete cells in column B (and shift-left) if the cell is empty?

Below is what I have but it's giving an "Application-defined or Object-defined error"

Sub DeleteCellShiftLeft()
    For i = 1000 To 1 Step -1
        If (Cells(i, B).Value = "") Then
        Cells(i, B).Delete shift:=xlToLeft
        End If
    Next i
End Sub
like image 571
Alex Millar Avatar asked Oct 21 '25 11:10

Alex Millar


2 Answers

A simpler and faster option, using Specialcells(xlCellTypeBlanks):

Sub DeleteCellShiftLeft()  
    dim rng as range  
    for each rng in range("B1:B1000").Specialcells(xlCellTypeBlanks)  
        rng.Delete shift:=xlToLeft  
    next rng  
End sub  
like image 148
iDevlop Avatar answered Oct 23 '25 08:10

iDevlop


You just need to add quotes around your column reference as follows:

Sub DeleteCellShiftLeft()
    For i = 1000 To 1 Step -1
        If (Cells(i, "B").Value = "") Then
        Cells(i, B).Delete shift:=xlToLeft
        End If
    Next i
End Sub
like image 28
Gove Avatar answered Oct 23 '25 07:10

Gove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!