选择性复制并粘贴给定条件的行

时间:2019-05-28 14:46:59

标签: excel vba

我试图根据J列中出现的“是”一词来选择表中的行。

我有一个表格,从A列到J列,我想选择J列中有“是”的行,并将这些行仅粘贴到新表中。

选择后,我需要将这些行复制到新的图纸或Word文档中。

我已经尝试过使用VBA宏对Windows MS Excel软件进行一系列论坛讨论。

我正在使用以下VBA,但出现问题:

Sub Macro1()
 Dim rngJ As Range
    Dim cell As Range

    Set rngJ = Range("J1", Range("J65536").End(xlUp))
    Set wsNew = ThisWorkbook.Worksheets.Add

    For Each cell In rngJ
        If cell.Value = "Yes" Then
            cell.EntireRow.Copy

            wsNew.Sheets("Sheet1").Range("J65536").End(xlUp).Offset(1, 0).Select

            ActiveSheet.Paste
        End If
    Next cell

End Sub

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

使用类似这样的东西

Option Explicit

Public Sub CopyYesRowsToNewWorksheet()
    Dim wsSource As Worksheet
    Set wsSource = ThisWorkbook.ActiveSheet 'better define sheet by name ThisWorkbook.Worksheets("SourceSheet")

    Dim DataRangeJ As Variant 'read "yes" data into array for faster access
    DataRangeJ = wsSource.Range("J1", wsSource.Range("J" & wsSource.Rows.Count).End(xlUp)).Value

    Dim wsNew As Worksheet
    Set wsNew = ThisWorkbook.Worksheets.Add

    Dim NextFreeRow As Long
    NextFreeRow = 1 'start pasting in this row in the new sheet

    If IsArray(DataRangeJ) Then        
        Dim iRow As Long
        For iRow = LBound(DataRangeJ) To UBound(DataRangeJ) 'loop through data array
            If DataRangeJ(iRow, 1) = "yes" Then
                wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value 'copy the values of the row
                NextFreeRow = NextFreeRow + 1
            End If
        Next iRow
    ElseIf DataRangeJ = "yes" Then 'if only the first row has data
        wsNew.Rows(NextFreeRow).Value = wsSource.Rows(1).Value
    End If
End Sub

wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value

仅复制值而不格式化。如果您还想复制格式,请替换为

wsSource.Rows(iRow).Copy Destination:=wsNew.Rows(NextFreeRow)

答案 1 :(得分:0)

与其查找,复制和粘贴每个单元格,不如查找所有单元格,然后像这样复制并粘贴一次:

Sub Macro1()
Dim rngJ As Range
Dim MySel As Range

Set rngJ = Range("J1", Range("J" & Rows.Count).End(xlUp))
Set wsNew = ThisWorkbook.Worksheets.Add

For Each cell In rngJ
    If cell.Value = "Yes" Then
        If MySel Is Nothing Then
            Set MySel = cell.EntireRow
        Else
            Set MySel = Union(MySel, cell.EntireRow)
        End If
    End If
Next cell

If Not MySel Is Nothing Then MySel.Copy Destination:= wsNew.Range("A1")
End Sub

最好避免尽可能多地使用Select;参见此link