【问题标题】:VBA insert new rows if 2 conditions met如果满足 2 个条件,VBA 插入新行
【发布时间】:2017-03-24 04:56:42
【问题描述】:

我想要实现的是在 A 列文本“丰富”中包含的某些行之后插入新行数,如果同一行中的 B 列包含小于 10 的值,则在该行之后插入 2 行。但如果同一行中的 B 列包含更高的值,则在该行之后插入 1 行。我在编写循环代码方面不是最好的。我将不胜感激。

【问题讨论】:

标签: excel vba


【解决方案1】:

一段时间后我设法做到了:)

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

【讨论】:

  • 在你第一个if不应该是CurrentRow = CurrentRow + 2吗?
  • 你也可以把Range("A" &amp; CurrentRow + 1).EntireRow.Insert xlIp改成Rows(CurrentRow + 1 &amp; ":" &amp; CurrentRow + 2).Insert
  • 代码是正确的,但是学习更快的方法来实现相同的结果永远不会有任何害处。
  • 是的,这是真的。谢谢你的建议:)
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 2023-01-31
相关资源
最近更新 更多