根据多个条件复制行

时间:2015-03-05 08:18:31

标签: vba excel-vba excel

我的代码只复制满足我设置的两个条件的第一行,然后停止,不知道我错在哪里。

代码用于复制行,如果值为" Active"可在列标题"状态"下找到。列标题是动态的,因此我必须相应地对其进行编码。

以下是代码:

   Sub copystatus()
        Dim LR as long
        Dim LC as integer
        Dim ws as worksheet
        Dim ws2 as worksheet



        Set ws = thisworkbook.sheets("Data")
        Set ws2 = thisworkbook.sheets("Target")

        LR = ws.cells(rows.count,1).end(xlup).row
       LC = ws.cells(1,columns.count).end(xltoleft).column

      With ws
          For x = 1 to LC
           If .cells(1,x).value = "Status" then
              For i = 2 to LR
                   If .cells(I,x).value = "Active" then
                Rows(i).copy destination:=ws2.range("A:L")
                   End if
              Next 
          End if
      Next
     End with

 End sub

2 个答案:

答案 0 :(得分:0)

您需要动态更改复制目标范围。它总是会将您的结果复制到相同的单元格中,并且会被覆盖。

尝试使用类似的内容复制行LR(目标表中没有空白行)和第1列

LR2 = ws2.cells(rows.count,1).end(xlup).row
Rows(i).Copy Destination:=ws2.Cells(LR2, 1)

答案 1 :(得分:0)

我自己已经解决了这个问题,这是代码的最终版本,以备你需要时使用。我了解到对象行也有一个值属性,就像cell / range一样,可以用相同的方式改变

   Sub copystatus()

       Dim LR as long
       Dim LC as integer
       Dim LR2 as Long
       Dim ws as worksheet
       Dim ws2 as worksheet



      Set ws = thisworkbook.sheets("Data")
      Set ws2 = thisworkbook.sheets("Target")

      LR = ws.cells(rows.count,1).end(xlup).row
      LC = ws.cells(1,columns.count).end(xltoleft).column

      With ws
         For x = 1 to LC
           If .cells(1,x).value = "Status" then
              For i = 2 to LR
                If .cells(I,x).value = "Active" then
                        LR2 = ws2.Cells(Rows.Count, 1).End(xlUp).Row
                        ws2.Rows(LR2 + 1).Value = .Rows(x).Value
                End if
              Next 
          End if
         Next
     End with

  End sub