Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

Excel VBA Delete Rows

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...