过滤数据并将其从一张纸复制到另一张纸

时间:2019-04-10 11:47:19

标签: excel vba

我在从工作簿的第一张工作表中筛选日期,然后将所有内容复制到另一个工作簿中时遇到问题。在代码的第一部分中,我选择了要使用的工作簿。当我运行我的代码时,它只是复制所有数据,而没有过滤它,我也不知道这是怎么回事。

Sub macro()

Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim LastRow As Long

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

    Sheets("Sheet1").Activate

    LastRow = Range("A1").CurrentRegion.Rows.Count
    Range("A1:CA" & LastRow).Select

    Selection.AutoFilter Field:=39, Criteria1:=Array( _
        "0", "1", "2", "3"), Operator:=xlFilterValues

    Selection.AutoFilter Field:=12, Criteria1:=">=1/1/2018", _
                        Operator:=xlFilterValues, _
                        Criteria2:="<=12/31/2019"
    Selection.Copy
    Cells.Select

    Dim dest As Range
    With Workbooks("data.xlsm").Worksheets(3)

    Sheets("data").Range("A:CA").ClearContents

    Set dest = .Range("A1")
    Selection.Copy dest
    End With
    Selection.AutoFilter
' Close customer workbook
customerWorkbook.Close False

End Sub

1 个答案:

答案 0 :(得分:0)

您只需要在代码中添加Selection.SpecialCells(xlCellTypeVisible).Copy而不是Selection.Copy。