0

I have a sub like this:

 Sub deleteExcessData(selectSheet As String, selectRow As Integer)   
    'selectSheet = go to a certain sheet
    'selectRow = go to a certain row

 End Sub

What I want to do with this is select a row to start, then select all the non-blank rows below that row all the way to the bottom, then delete that selection. (this can include the row or not include that row)

I only want to use 2 variables in this sub, one is to select the sheets and on is used to select the anchor row. Data is contiguous.

What if there are some random blank cells in the data?

Any suggestion?

1
  • A modern Excel worksheet has 1,048,576 rows. Change selectRow As Integer to selectRow As Long. Commented Jul 7, 2015 at 17:51

2 Answers 2

1

Try something like this:

Sub deleteExcessData(selectSheet As String, selectRow As Integer)
    lastRow = Worksheets(selectSheet).Cells(1, 1).End(xlDown).Row
    Worksheets(selectSheet).Rows(selectRow & ":" & lastRow).Delete
End Sub

If you need to go up from the bottom, try this:

Sub deleteExcessData(selectSheet As String, selectRow As Integer)
    lastRow = Worksheets(selectSheet).Cell(Row.Count, 1).End(xlUp).Row
    Worksheets(selectSheet).Rows(selectRow & ":" & lastRow).Delete
End Sub
Sign up to request clarification or add additional context in comments.

8 Comments

And be sure to try this out on some test data first.
how should I do it if there are a few blank cells in the data?
I believe your first sub only deletes row 1,048,576. You have not extended the range reference from the start to the bottom.
So I tried your code (the first part) with this: Call deleteExcessData("data", 5) and it gives me "object does not support this property or method". And your second code gives me "object required" on the second row. I already declared a global lastRow variable as Long.
Does it point you to a line where the error occurs? Also be sure to try @Jeeped's answer.
|
0

This should remove all rows to the bottom of the worksheet including the row being called.

Sub test()
    Call deleteExcessData("Sheet1", 9)
End Sub

Sub deleteExcessData(selectSheet As String, selectRow As Long)
    With Sheets(selectSheet).Cells(selectRow, 1)
        .Resize(Rows.Count - selectRow + 1, 1).EntireRow.Delete
    End With
End Sub

The above removes all rows from 9:1048576.

You could alternately pass across the worksheet object rather than the name if that is already defined by the calling sub.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.