Scott Conover
Scott Conover

Reputation: 1421

Curious Delete Behavior with Command Button VBA

I am continuing my efforts with data pulled from a mainframe. Currently, I am continuing work on sorting data for use in forms and potential data processing and the like. The data is alphanumeric and is similar in form to one of my previous questions related to my continuing data efforts.

One of my current development lines involved increased usability in the form of macro-enabled buttons. One such button involves a macro which is intended to delete all data in one column "A" from A2 to the end of any existing datarows in the sheet.

The code is as follows:

Sub DeleteCriteria_Click()

Dim CriteriaRange As Range

Dim LastCriteriaCell As Long

With Sheets("Criteria")
    LastCriteriaCell = .Range("A" & Sheets("Criteria").Rows.Count).End(xlUp).Row
    Set CriteriaRange = .Range("A2:A" & LastCriteriaCell)
End With

CriteriaRange.Cells.Select

Selection.Delete

End Sub

Curiously, this code ends up shifting my columns over by one each time I activate the button, and ends up deleting my header and subsequent columns with repeated clicks. This behavior resembles that of a normal delete function for a column. Refactoring the range commands CriteriaRange.Cells.Select | Selection.Delete into the forms CriteriaRange.Cells.Delete and CriteriaRange.Delete does not correct this issue.

My intent is to completely delete the entries so that there are no blanks or leftover datasets when new criteria is entered after the entries are deleted. I thus have two questions:

1) What is causing this behavior, i.e. what I am doing incorrectly, here?

2) How do I correct this behavior to utterly delete the cells or functionally perform the equivalent, thereby prevent any references to blank or null cells, while retaining my column?

Upvotes: 2

Views: 1103

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149287

Change your code to

CriteriaRange.Delete Shift:=xlUp

The default is

CriteriaRange.Delete Shift:=xlToLeft

Because of this your columns are moved.

Your code can be written as

Sub DeleteCriteria_Click()
    Dim LastCriteriaCell As Long

    With Sheets("Criteria")
        LastCriteriaCell = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> This is required so that your header cells are not touched
        If LastCriteriaCell < 2 Then Exit Sub

        .Range("A2:A" & LastCriteriaCell).Delete Shift:=xlUp
    End With
End Sub

OR

Sub DeleteCriteria_Click()
    Dim LastCriteriaCell As Long

    With Sheets("Criteria")
        LastCriteriaCell = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> This is required so that your header cells are not touched
        If LastCriteriaCell >= 2 Then _
        .Range("A2:A" & LastCriteriaCell).Delete Shift:=xlUp
    End With
End Sub

Upvotes: 2

Related Questions