将突出显示的绿色复制到另一个工作表

时间:2017-11-22 08:32:45

标签: excel vba excel-vba

我设法在同一张纸上复制单元格。但这不是我的主要意图。我应该能够将突出显示的单元格复制到另一个工作表,如Sheet2或Sheet3。我该怎么做?

以下是我在同一张纸上复制的内容 Click here to see image

Sub copyHighlight()
    Dim ws As Worksheet
    Dim lr As Long, i As Long, u As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    With ws
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        If 2 > lr Then Exit Sub

        u = 2
        For i = 2 To lr
            If .Cells(i, 1).Interior.ColorIndex = 4 Then
                .Cells(i, 1).Copy .Cells(u, "E")
                u = u + 1
            End If
        Next i
    End With

    Set ws = Nothing
End Sub

2 个答案:

答案 0 :(得分:2)

找出如何只复制某些细胞的好工作,这让很多人感到难过。

微小变化:添加Sheets("Sheet2")如下:

Sub copyHighlight()
    Dim ws As Worksheet
    Dim r As Long, i As Long, u As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    With ws
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        If 2 > lr Then Exit Sub

        u = 2
        For i = 2 To lr
            If .Cells(i, 1).Interior.ColorIndex = 4 Then
                .Cells(i, 1).Copy Sheets("Sheet2").Cells(u, "E")
                u = u + 1
            End If
        Next i
    End With

    Set ws = Nothing
End Sub

答案 1 :(得分:1)

你的代码非常好,要实现你想要的东西,你只需要参考其他一些工作表,如下图所示(我复制了你的代码并添加了部分以使其工作)。

Sub copyHighlight()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim r As Long, i As Long, u As Long

Set ws1 = ThisWorkbook.Worksheets("Sheet1")
'here you set reference to another worksheet
Set ws2 = ThisWorkbook.Worksheets("Sheet2")

With ws1
    lr = .Cells(Rows.Count, 1).End(xlUp).Row
    If 2 > lr Then Exit Sub

    u = 2
    For i = 2 To lr
        If .Cells(i, 1).Interior.ColorIndex = 4 Then
            .Cells(i, 1).Copy ws2.Cells(u, "E") 'NOTE, that here we used reference to another worksheet
            u = u + 1
        End If
    Next i
End With

Set ws1 = Nothing
Set ws2 = Nothing
End Sub