Excel表达式复制行但删除空白行

Joh*_*ore 1 excel vba excel-vba excel-formula

我需要将数据从一个工作表复制到另一个工作表。但是,我需要一个条件复制操作,该操作将根据条件跳过行。

例如,如果我从...开始

Active  Value
yes     1
no      2
no      3
yes     4
no      5
no      6
Run Code Online (Sandbox Code Playgroud)

我只想复制Active = yes的行,所以最终结果是...

Value
1
4
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何通过1)宏和2)公式来实现此目的吗?

Dmi*_*liv 5

公式方法:

假设您的数据在sheet1的范围内A2:B7

然后在sheet2单元格中使用此公式A2

=IFERROR(INDEX(Sheet1!B:B,SMALL(IF(Sheet1!$A$2:$A$7="yes",ROW(Sheet1!$A$2:$A$7)),ROW()-ROW($A$2)+1)),"")
Run Code Online (Sandbox Code Playgroud)

使用数组条目(CTRL+ SHIFT+ ENTER),然后将其向下拖动。

在此处输入图片说明

VBA方法:

您可以使用AutoFilter

Sub test()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim rng As Range, rngToCopy As Range
    Dim lastrow As Long
    'change Sheet1 and Sheet2 to suit
    Set ws1 = ThisWorkbook.Worksheets("Sheet1")
    Set ws2 = ThisWorkbook.Worksheets("Sheet2")

    With ws1
        'assumung that your data stored in column A:B, Sheet1
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Set rng = .Range("A1:B" & lastrow)
        'clear all filters
        .AutoFilterMode = False
        With rng
            'apply filter
            .AutoFilter Field:=1, Criteria1:="yes"
            On Error Resume Next
            'get only visible rows
            Set rngToCopy = .SpecialCells(xlCellTypeVisible)
            On Error GoTo 0
        End With
        'copy range
        If Not rngToCopy Is Nothing Then rngToCopy.Copy Destination:=ws2.Range("A1")
        'clear all filters
        .AutoFilterMode = False
    End With
    Application.CutCopyMode = False
End Sub
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

注意,如果只想复制Value列,请更改

Set rngToCopy = .SpecialCells(xlCellTypeVisible)
Run Code Online (Sandbox Code Playgroud)

Set rngToCopy = .Offset(, 1).Resize(, .Columns.Count - 1).SpecialCells(xlCellTypeVisible)
Run Code Online (Sandbox Code Playgroud)