如果符合2个条件,VBA插入新行

14 浏览
0 Comments

如果符合2个条件,VBA插入新行

我想要实现的是,在包含A列中文本“rich”的某些行之后插入新行的数量,如果同一行中的列B包含小于10的值,则插入2行。但是,如果同一行中的列B包含更高的值,则在此行之后插入1行。我并不是写循环代码的高手。我将感激任何帮助。

admin 更改状态以发布 2023年5月24日
0
0 Comments

经过一段时间的努力,我终于完成了 🙂

Sub macro1()
    Range("A1").Select
    ' remember the last row that contains a value
    Dim LastRow As Integer
    Dim CurrentRow As Integer
    LastRow = Range("A1").End(xlDown).Row
    CurrentRow = 1
    ' keep on incrementing the current row until we are
    ' past the last row
    Do While CurrentRow <= LastRow
        ' if the desired string is found, insert a row above
        ' the current row
        ' That also means, our last row is going to be one more
        ' row down
        ' And that also means, we must double-increment our current
        ' row
        If Range("A" & CurrentRow).Value = "rich" And Range("B" & CurrentRow).Value > 10 Then
            Range("A" & CurrentRow + 1).EntireRow.Insert xlIp
            Range("A" & CurrentRow + 1).EntireRow.Insert xlIp
            LastRow = LastRow + 2
            CurrentRow = CurrentRow + 1
        ElseIf Range("A" & CurrentRow).Value = "rich" And Range("B" & CurrentRow) < 10 Then
            Range("A" & CurrentRow + 1).EntireRow.Insert xlUp
            LastRow = LastRow + 1
            CurrentRow = CurrentRow + 1
        End If
        ' put the pointer to the next row we want to evaluate
        CurrentRow = CurrentRow + 1
    Loop
End Sub

0