user1204868
user1204868

Reputation: 606

Error with deleting 1 row after doing some checks

I have a problem trying to delete an entire row using the code as below:

Sub Macro1()
    Dim test1row As Long, test1 As Range, firstrowtodelete As Long

    test1row = 1

    Do 
        Set test1 = Sheets("Sheet1")l.Cells(test1row,1)

        If test1 <> "actest" Or test1 <> "dctest" Then
            firstrowtodelete = test1row
            Rows(test1row).Select
            Selection.Delete Shift:=xlUp
            Exit Do
        End If

        test1row = test1row + 1
    Loop
End Sub

The error is with Rows(test1row).Select. It deletes the row even if it is "actest" or "dctest". If you know why do share with me! thanks! :)

Upvotes: 0

Views: 115

Answers (2)

Drew Gaynor
Drew Gaynor

Reputation: 8472

There are two problems with your code.

The first problem is on this line:

Set test1 = Sheets("Sheet1")l.Cells(test1row,1)

It should be:

Set test1 = Sheets("Sheet1").Cells(test1row, 1)

And the other problem is here:

If test1 <> "actest" Or test1 <> "dctest" Then

It should be this:

If test1 <> "actest" And test1 <> "dctest" Then

Your If statement would always be true. Using the And operator will give you a true value only when the cell's value isn't "actest" and it isn't "dctest" which is presumably the desired behavior.

Here is the complete working code:

Sub Macro1()
    Dim test1row As Long, test1 As Range, firstrowtodelete As Long

    test1row = 1

    Do
        Set test1 = Sheets("Sheet1").Cells(test1row, 1)

        If test1 <> "actest" And test1 <> "dctest" Then
            firstrowtodelete = test1row
            Rows(test1row).Select
            Selection.Delete Shift:=xlUp
            Exit Do
        End If

        test1row = test1row + 1
    Loop
End Sub

Upvotes: 1

chris neilsen
chris neilsen

Reputation: 53126

Your If test is flawed. It will always be true.

Upvotes: 1

Related Questions