过滤数据并将该数据的值粘贴到另一个工作表中

时间:2013-10-09 09:32:10

标签: excel vba filter

我有一个复杂的问题...... 我已将.csv文件中的数据导入工作表(导入的数据)。现在在另一个工作表(导入函数)中,我使用一个按钮作为宏来过滤掉某些数据。过滤器取决于在单元格A2,单元格B2,单元格C2中填充的数据(这些过滤器由excel的用户填写)。如果这些过滤器与工作表(导入的数据)中的行匹配,则应将这些值粘贴到另一个工作表上。我该怎么做呢? A2,B2和C2中的这些过滤器与另一个工作表中的A,B,C匹配

提前......

作为回复,我现在有了代码:

Sub FilterButton()
If MsgBox("Are you sure the fields 'Collection' and 'System' are filled in?", vbInformation + vbYesNo, "Sort function") = vbYes Then
    'If vbYesNo = Yes Then'

Dim ws1, ws2, ws3 As Worksheet
Dim filter1, filter2, filter3 As String
Dim lrow As Double

Set ws1 = ThisWorkbook.Sheets("Import") 'this contains the filters
Set ws2 = ThisWorkbook.Sheets("Imported Data") 'this contains the text file
Set ws3 = ThisWorkbook.Sheets("Test") ' this is the destination

With ws1
    filter1 = "=" & .Range("A2").Value
    filter2 = "=" & .Range("B2").Value
    filter3 = "=" & .Range("C2").Value
End With

With ws2
    lrow = .Range("A" & .Rows.Count).End(xlUp).Row

With .Range("A1:G" & lrow)
        .AutoFilter Field:=1, Criteria1:=filter1
        .AutoFilter Field:=2, Criteria1:=filter2
        .AutoFilter Field:=3, Criteria1:=filter3
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
        ws3.Cells(.Range("A" & .Rows.Count).End(xlUp).Row + 1, 1)
End With

.AutoFilterMode = False

End With

End If

End Sub

我的搜索条件(来自ws1的A2,B2,C2与ws2(A2,B2,C2)的搜索条件匹配但是它没有被ws3所取代?我做错了什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

Option Explicit
Sub test()

Dim ws1, ws2, ws3 As Worksheet
Dim filter1, filter2, filter3 As String
Dim lrow As Double


Set ws1 = ThisWorkbook.Sheets("Sheet1") 'this contains the text file
Set ws2 = ThisWorkbook.Sheets("Sheet2") 'this contains the filters
Set ws3 = ThisWorkbook.Sheets("Sheet3")' this is the destination

With ws2
    filter1 = "=" & .Range("A2").Value
    filter2 = "=" & .Range("B2").Value
    filter3 = "=" & .Range("C2").Value
End With

With ws1
    lrow = .Range("A" & .Rows.Count).End(xlUp).Row

With .Range("A1:O" & lrow)
        .AutoFilter Field:=5, Criteria1:=filter1
        .AutoFilter Field:=8, Criteria1:=filter2
        .AutoFilter Field:=14, Criteria1:=filter3
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
        ws3.Cells(.Range("A" & .Rows.Count).End(xlUp).Row + 1, 1)
End With

.AutoFilterMode = False

End With

End Sub

我只假设了列数(A到O)
我只假设您需要过滤的字段编号。 (5,8,14)
根据您的需要进行更改 希望这能让你开始。