【问题标题】:'If Then' loop with copy and paste'If Then' 循环复制和粘贴
【发布时间】:2016-01-10 00:38:46
【问题描述】:

我目前有一小部分 VBA 可以搜索条件并根据条件进行基本添加。效果很好,如下:

Dim i As Long
i = 6
Do While Cells(i, "C").Value <> ""
If Cells(i, "C").Value = "9/12/2015" And Cells(i, "E").Value = "9/13/2015" Then
        Cells(i, "M").Value = Cells(i, "M").Value + 12
End If
i = i + 1
Loop

我现在想将其提升到一个新的水平,而不是根据条件将 12 添加到列中,而是执行以下操作:

-选择所有满足这两个条件的行,并将它们的值从 Sheet1 复制并粘贴到 Sheet2

我认为复制和粘贴部分会非常简单,但我不确定根据 if...then 语句的结果选择不同行的最佳方法。

【问题讨论】:

    标签: excel vba loops if-statement copy-paste


    【解决方案1】:
    Dim i As Long: i = 6
    Dim r as Range
    
    Do While Cells(i, "C").Value <> ""
      If Cells(i, "C").Value = "9/12/2015" And Cells(i, "E").Value = "9/13/2015" Then
        if r is nothing then
          set r = Cells(i, "M")
        else
          set r = application.union(r, Cells(i, "M"))
        end if
      End If
    
      i = i + 1
    Loop
    
    if not r is nothing then
      r.Copy Sheet2.Range("A1")
    end if
    

    【讨论】:

    • 感谢 GSerg 的输入——我从未使用过 application.union 片段,它有什么作用?同样对于下一位代码,列 M 无关紧要。我只需要它来选择“If Then”语句为真的所有行,然后将这些行复制并粘贴到另一个工作表中。
    • @Willarci3 然后使用Cells(i, "M").EntireRow 而不仅仅是Cells(i, "M") 建立范围。
    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2019-01-23
    • 2016-11-09
    相关资源
    最近更新 更多