1

I am trying to create a program that will delete or create rows based on what a user puts in a certain row. For example, if the user puts in 3, but there are only 2 rows, then it will insert 1 row. If there were 5 rows, it would delete rows 4 and 5. It seems like it should be an easy code, but I am having the hardest time having it actually delete/create the rows that I want it to. My code is as follows:

Sheets("Summary").Select

x = Cells(29, 3).Value
i = 7

Sheets("Weighted I").Select

Do Until Cells(i, 1).Value = "TOTAL"
    i = i + 1
Loop

i = i - 7
If i > x Then   
    dlt = i - x + 7

    For cnt = 7 To dlt
        Rows(cnt).EntireRow.Delete
        cnt = cnt + 1
    Next    
ElseIf i < x Then
    crt = x - i + 7

    For cnt = 7 To dlt
        Rows(cnt).EntireRow.Insert
        cnt = cnt + 1
    Next
End If
0

1 Answer 1

3

This is a common problem when deleting rows. Imagine you are moving through your for loop one row at a time and deleting:

For cnt = 7 To dlt
    Rows(cnt).EntireRow.Delete
    cnt = cnt + 1
Next 

You are on row 7 and you delete it. This shifts all of your rows up. Row 8 is now Row 7. You then increase your cnt variable by 1 (to 8) and delete row 8. But you missed row 7, which was row 8... it's crazy bananas.

Instead, change your for loop to work backwards:

For cnt = dlt to 7 step -1
    Rows(cnt).EntireRow.Delete
    cnt = cnt - 1
Next    

This way the row shifting doesn't affect your cnt.

Sign up to request clarification or add additional context in comments.

1 Comment

JNevill, that worked perfectly. Thank you, I knew it just had something to do with my logic in the code. Thank you so much for the help!

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.