Excel VBA删除行 [英] Excel VBA Delete Rows

查看:83
本文介绍了Excel VBA删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,该程序将根据用户在特定行中的内容来删除或创建行.例如,如果用户输入3,但是只有2行,则它将插入1行.如果有5行,它将删除第4行和第5行.这似乎应该是一个简单的代码,但是我很难让它实际删除/创建我想要的行.我的代码如下:

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

推荐答案

这是删除行时的常见问题.想象一下,您一次遍历for循环并删除:

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 

您位于第7行,并将其删除.这会将所有行上移.第8行现在是第7行.然后将cnt变量增加1(到8)并删除第8行.但是您错过了第7行,也就是第8行...这是疯狂的香蕉.

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.

相反,将for循环更改为向后工作:

Instead, change your for loop to work backwards:

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

这样,行移位不会影响您的cnt.

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

这篇关于Excel VBA删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆