vba 使用宏在记录集更改后插入多行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20077028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:32:05  来源:igfitidea点击:

Using a Macro to insert multiple rows after a change in recordset?

excelvbaexcel-vba

提问by user2945184

This is an inherited code, and I am no expert in VBA, in fact -- I've never used it. After toying around for a bit I felt that maybe someone could offer some much needed help.

这是一个继承的代码,事实上,我不是 VBA 专家——我从未使用过它。在玩了一会儿之后,我觉得也许有人可以提供一些急需的帮助。

Currently this VBA will add a row when there is a change in columnd D. This works fine, all I'm looking to augment is the number of rows inserted. Lets say instead of 1, I'd like 4 rows inserted. Where in the code would I make these chanegs?

目前,当 D 列发生变化时,此 VBA 将添加一行。这很好用,我想要增加的只是插入的行数。让我们说而不是 1,我想要插入 4 行。我会在代码中的哪个位置进行这些更改?

Sub InsertRowAtChangeInValue()

Dim lRow As Long

' Break line at USD / Local

For lRow = Cells(Cells.Rows.Count, "D").End(xlUp).Row To 2 Step -1
If Cells(lRow, "D") <> Cells(lRow - 1, "D") Then Rows(lRow).EntireRow.Insert
Next lRow

I am assuming it would have to be somehwere in the Then Rows(lRow).EntireRow.Insertbut everything I try seems to not work.

我假设它必须在某个地方,Then Rows(lRow).EntireRow.Insert但我尝试的一切似乎都不起作用。

If you could also explain why what you suggested worked, that would also be helpful so I no longer need to rely on the community. Thanks

如果您还可以解释为什么您的建议有效,那也会有所帮助,因此我不再需要依赖社区。谢谢

采纳答案by Howard Renollet

This is the fastest way:

这是最快的方法:

Sub InsertRowAtChangeInValue()

    Dim lRow As Long

    ' Break line at USD / Local

    For lRow = Cells(Cells.Rows.Count, "D").End(xlUp).Row To 2 Step -1
        If Cells(lRow, "D") <> Cells(lRow - 1, "D") Then
            Rows(lRow).EntireRow.Insert
            Rows(lRow).EntireRow.Insert
            Rows(lRow).EntireRow.Insert
            Rows(lRow).EntireRow.Insert
        End If
    Next lRow
End Sub