【问题标题】:How to copy one specific column after filtering results with Autofilter - VBA如何在使用自动过滤器过滤结果后复制一个特定的列 - VBA
【发布时间】:2020-04-23 22:13:19
【问题描述】:

经过几个小时的尝试,我急需帮助。我是 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

提前谢谢你:)

【问题讨论】:

  • Cells(count_row, 20).SpecialCells(xlCellTypeVisible).Copy - 如果您在一个单元格上调用 SpecialCells,它将返回所有内容...在列上调用它。虽然我不确定orig.Range("T1") = 在那里做什么。

标签: excel vba copy autofilter


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复。我尝试了上面的代码,但出现语法错误。
  • @Mika - 哪一行?
  • count_col = WorksheetFunction.CountA(orig.Range("A1"), orig.Range("A1").End(xlToRight))) count_row = WorksheetFunction.CountA(orig.Range("A1 "), orig.Range("A1").End(xlDown)))
  • 如有必要,我可以发布文件。
  • 非常感谢!你是最棒的。这解决了我的问题。非常感谢!我对这个领域很陌生,我什至不是新手。但再次感谢您!
猜你喜欢
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
相关资源
最近更新 更多