如何使用vba在指定列中包含“2024”的每一行下方插入一行,并在该新行中在同一列中输入“2025”?

问题描述 投票:0回答:1

我正在从 ERP 系统下载销售历史记录,并想为明年的预测添加一行。
ERP导出图片:

enter image description here

..如文字:

Employee.Employee   Company Product Year    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total

Employee.1  Customer A  Product A   2023                                1                   1

Employee.1  Customer A  Product A   2024                        2                           2

Employee.1  Customer A  Product B   2024                        4                           4

Employee.1  Customer A  Product C   2024                        5                           5

Employee.1  Customer A  Product D   2024                        3                           3

Employee.1  Customer A  Product E   2024                        3                           3

Employee.1  Customer A  Product F   2023                                39  22              61

Employee.1  Customer A  Product F   2024                        19                          19

我没有接受过 VBA 培训,只是知道有比手动更好的方法。感谢任何帮助/建议。 以下适用于添加空白行。现在如何将“2025”输入到新插入行的 D 列中?

Sub Macro1()
    Dim RngToCheck As Range
    Set RngToCheck = ThisWorkbook.Sheets("Invoiced Tons by Customer by Mo").Range("D3:D5000")
    Dim ValToFind As Long
    ValToFind = 2024

    Dim i As Long
    For i = RngToCheck.Rows.Count To 1 Step -1
        If RngToCheck(i).Value = ValToFind Then
            RngToCheck(i + 1).EntireRow.Insert
        End If
    Next i
End Sub
excel vba
1个回答
0
投票

试试这个:

Sub Macro1()
    Dim ws As Worksheet, RngToCheck As Range, ValToFind As Long, i As Long
    
    Set ws = ThisWorkbook.Worksheets("Invoiced Tons by Customer by Mo")
    
    Set RngToCheck = ws.Range("D3:D" & ws.Cells(Rows.Count, "D").End(xlUp).Row)
    ValToFind = 2024

    Application.ScreenUpdating = False
    For i = RngToCheck.Cells.Count To 1 Step -1
        With RngToCheck.Cells(i)
            If .Value = ValToFind Then
                .offset(1).EntireRow.Insert
                .offset(1).Value = 2025
            End If
        End With
    Next i
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.