在VBA中动态插入一行并迭代它?

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

在一系列单元格的反向迭代期间(从下到上,从右到左),将在当前单元格上方插入一行并向下移动。

Sub ReverseIterateAndInsertRowRestart()
    Dim ws As Worksheet
    Dim rng As Range
    Dim r As Long, c As Long
    Dim columnToCheck As Long
    Dim startRow As Long, startColumn As Long

    ' Set the worksheet and define the initial range
    Set ws = ActiveSheet
    Set rng = ws.Range("A1:E10") ' Adjust as needed

    ' Initialize starting row and column
    startRow = rng.Rows.Count
    startColumn = rng.Columns.Count

    ' Iterate through each row from bottom to top
    For r = startRow To 1 Step -1
        ' Iterate through each column from right to left
        For c = startColumn To 1 Step -1
            ' Check if the cell is blank
            If Not IsEmpty(rng.Cells(r, c)) Then
                ' Insert a copy of the current row above
                rng.Rows(r).Copy
                rng.Rows(r).Insert Shift:=xlDown
                rng.Cells(r, c).ClearContents ' Clear the specific cell in the copied row

                ' Update the range to include the new row
                Set rng = ws.Range(rng.Cells(1, 1), rng.Cells(rng.Rows.Count, rng.Columns.Count))

                ' Adjust the row counter to account for the new row
                r = r + 1
            End If
        Next c
    Next r
End Sub

如何确保迭代继续到新创建的行(就好像它已经存在一样)?尝试添加

r=r+1
但没有运气。似乎无法更新循环。

excel vba excel-2021
1个回答
0
投票

解决方案如下:

    Dim i As Long
    ' Iterate through each row from bottom to top
    For r = startRow To 1 Step -1
        ' Iterate through each column from right to left
        i = r
        For c = startColumn To 1 Step -1
            ' Check if the cell is blank
            If Not IsEmpty(rng.Cells(i, c)) Then
                ' Insert a copy of the current row above
                rng.Rows(r).Copy
                rng.Rows(r).Insert Shift:=xlDown
                rng.Cells(r, c).ClearContents ' Clear the specific cell in the copied row

                ' Update the range to include the new row
                'Set rng = ws.Range(rng.Cells(1, 1), rng.Cells(rng.Rows.Count, rng.Columns.Count))

                ' Adjust the row counter to account for the new row
                i = i + 1
            End If
        Next c
    Next r
© www.soinside.com 2019 - 2024. All rights reserved.