Excel VBA,复制彩色行

时间:2018-05-05 17:54:45

标签: excel vba excel-vba

我在" Sheet1"中有一个列表有三列,A(帐号),B(描述)& C(金额)。基于前两列(A& B)颜色,我想将特定行复制到" Sheet2"并将其粘贴到一个特定的标题下(我有三个标题)。

实施例

  1. Sheet1 - 单元格A2是"红色" &安培; B2是"黄色",在标题下复制/粘贴"效率低下"在Sheet2
  2. Sheet1 - Cell A3是" Blue" &安培; B3是"没有颜色"复制/粘贴在标题下#34;有效"在Sheet2
  3. Account Number  Description  Amount
    LP001022        Graduate     3,076.00 
    LP001031        Graduate     5,000.00 
    LP001035        Graduate     2,340.00 
    

    我已经从这个网站上获取了代码,但我无法根据自己的需要对其进行完全配置。感谢您的帮助。

    Sub lastrow()
        Dim lastrow As Long
        Dim i As Long, j As Long
        Dim acell As Range
    
        With Worksheets("Sheet1")
            lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        End With
    
        MsgBox (lastrow)
    
        With Worksheets("Sheet3")
            j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
        End With
    
        For i = 1 To lastrow
            With Worksheets("Sheet1")
                If .Cells(i, 1).Interior.Color = RGB(255, 255, 0) And _
                   .Cells(i, 1).Interior.ColorIndex = xlNone Then
                       .Rows(i).Copy 'I have to give destination 
                       j = j + 1
                    End If
            End With
        Next i
    End Sub
    

1 个答案:

答案 0 :(得分:2)

以下是将sheet1中的行复制到INSERT到sheet2中的行的关键指令。假设您拥有所有行号。

' -- to copy a row in sh1 to INSERT into sh2:
  sh2.Rows(irowInefficiency + 1).Insert
  sh1.Rows(irowFrom).Copy sh2.Rows(irowInefficiency + 1)
' -- you have to increment all header rows after this one
  irowEffective = irowEffective + 1

以下内容将这些内容放在上下文中:

Sub sub1() ' copy/insert a row
  Dim irowFrom&, irowInefficiency&, irowEffective&
  Dim sh1, sh2 As Worksheet
  Set sh1 = Sheets("sheet1")
  Set sh2 = Sheets("sheet2")
  irowInefficiency = 3 ' where that header is
  irowEffective = 6 ' where that header is
  irowFrom = 5 ' the row to copy
' -- to copy a row in sh1 to INSERT into sh2:
  sh2.Rows(irowInefficiency + 1).Insert ' a blank row
  sh1.Rows(irowFrom).Copy sh2.Rows(irowInefficiency + 1) ' then copy
' -- you have to increment all header rows after this one
  irowEffective = irowEffective + 1 ' because it increases
End Sub