如何在使用自动过滤器过滤结果后复制一个特定的列 - VBA

How to copy one specific column after filtering results with Autofilter - VBA

经过几个小时的尝试,我迫切需要帮助。我是 VBA 的新手,这是我的问题。 我有一个 table 有 20 列(A 到 T)但行数未定义(它们会随着时间的推移而增加),我的目标是根据 2 个条件过滤数据:第一个条件在第 6 列( F2) - 城市名称和第二个标准在第 11 列 (K2) - 月份,但没有格式化为时间,只是文本,之后我只想将第 20 列 (T2) 的可见结果复制到第二个 sheet 的工作簿。我的问题是,当我 运行 代码时,所有列都被复制(A 到 T)。 这是我使用的代码:

Sub copy_filtered_data()
Dim count_col, count_row As Integer
Dim orig, output As Worksheet


Worksheets("Intrari").Activate

Set orig = ThisWorkbook.Sheets("Intrari")
Set output = ThisWorkbook.Sheets("Raport")

count_col = WorksheetFunction.CountA(Range("A1", Range("A1").End(xlToRight)))
count_row = WorksheetFunction.CountA(Range("A1", Range("A1").End(xlDown)))

ActiveSheet.Range("A1").AutoFilter Field:=6, Criteria1:=Cells(2, 28).Value
ActiveSheet.Range("A1").AutoFilter Field:=11, Criteria1:=Cells(2, 29).Value

orig.Range("T1") = Cells(count_row, 20).SpecialCells(xlCellTypeVisible).Copy
output.Cells(1, 1).PasteSpecial xlPasteValues

Application.CutCopyMode = False

End Sub

提前谢谢你:)

这里有一些问题可能会给您带来麻烦,包括不合格的范围、语法问题和未类型化的变量。试试下面的代码。

Sub copy_filtered_data()

Dim orig as Worksheet, output As Worksheet

Set orig = ThisWorkbook.Sheets("Intrari")
Set output = ThisWorkbook.Sheets("Raport")

Dim count_col as Long, count_row As Long

count_col = orig.Cells(1,orig.Columns.Count).End(xlToLeft).Column
count_row = orig.Cells(orig.Rows.Count,1).End(xlUp).Row

orig.Range("A1").AutoFilter Field:=6, Criteria1:=orig.Cells(2, 28).Value
orig.Range("A1").AutoFilter Field:=11, Criteria1:=orig.Cells(2, 29).Value

orig.Range("T1:T" & count_row).SpecialCells(xlCellTypeVisible).Copy
output.Cells(1, 1).PasteSpecial xlPasteValues

End Sub