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

问题描述 投票:0回答:1

经过几个小时的尝试,我急需帮助。我是VBA新手,这是我的问题.我有一个表,有20列(A到T),但有一个未定义的行数(他们会随着时间的推移而增加),我的目标是基于2个标准过滤数据:第一个标准是在第6列(F2) - 城市名称和第二个标准是在第11列(K2) - 月份,但没有形成时间,只是文本,之后,我想只复制第20列(T2)的可见结果到工作簿的第二张表中。我的问题是,当我运行的代码,所有的列被复制(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

先谢谢你:)

excel vba copy autofilter
1个回答
0
投票

这里有几个问题可能会导致你的问题,包括非限定范围,语法问题和非类型变量。试试下面的代码。

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
© www.soinside.com 2019 - 2024. All rights reserved.