如何将excel 2007中突出显示的单元格从一个表格复制到同一张表格中的另一个表格?

时间:2015-07-23 08:32:03

标签: excel vba excel-vba excel-2007

我想在同一张表格中将突出显示的单元格从一个表格复制到另一个表格,但我使用的代码总是跳过最后一个单元格之前的单元格,如何编辑代码以复制所有突出显示的单元格,当我再次运行宏时,它只是更新第二个表?

这是代码:

Sub CopyCat()
  ActiveSheet.Unprotect Password:="P@ssw0rd"
Dim LR As Long, i As Long, j As Long
Dim c As Range
j = 1
LR = Range("A" & Rows.Count).End(xlUp).Row
For Each c In Worksheets("MB").Range("A15:I60" & LR)
      If c.Interior.ColorIndex = 3 Then
            c.Copy Destination:=Worksheets("MB").Range("J" & j)
        j = j + 1
        End If
Next c
  ActiveSheet.Protect Password:="P@ssw0rd"

End Sub

请帮助!!

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub CopyCat()

    With Sheets("Sheet1")

        'Unprotect sheet
        .Unprotect Password:="P@ssw0rd"

        Dim lastRow, row As Long
        Dim cell As Range

        row = 1

        'get last row should start from A15 because i think your table is start at A15.
        lastRow = .Range("A15").SpecialCells(xlCellTypeLastCell).row

        'loop all cell from desired range of "fromsheetname" sheet
        For Each cell In .Range("A15:G" & lastRow)

            If cell.Interior.ColorIndex = 3 Then

                cell.Copy Destination:=.Range("J" & row)

                row = row + 1

            End If

        Next cell

        'Protect sheet
        .Protect Password:="P@ssw0rd"

    End With

End Sub