简体   繁体   English

VBA中的Excel过滤和复制

[英]Excel Filtering and Copying in VBA

I'm working on a VBA script that pulls a range of dates from Access, then filters the data and creates a chart based on the filtered data.我正在处理一个 VBA 脚本,该脚本从 Access 中提取一系列日期,然后过滤数据并根据过滤后的数据创建图表。 The filtered data will be going to a separate sheet where the chart will be pulling its data from .过滤后的数据将转到单独的工作表,图表将从中提取其数据。 I can get data out of Access with a SQL statement, but my AutoFilter in Excel is erroring out.我可以使用 SQL 语句从 Access 中获取数据,但是我在 Excel 中的自动AutoFilter出错了。 Here is what I have...这是我所拥有的...

Sheet3.Range("F4:F500").AutoFilter(, "Riveter 01").Copy Destination:=Sheet2.Range("A5")

It gives an app-defined or object-defined error and I can't figure out why.它给出了应用程序定义或对象定义的错误,我不知道为什么。 Is this the proper way or is there an easier way?这是正确的方法还是有更简单的方法?

PS: This filter will happen with 22 unique machines so I was planning on running a loop for each machine. PS:这个过滤器将在 22 台不同的机器上发生,所以我计划为每台机器运行一个循环。 If that is not the fastest or proper way please let me know.如果这不是最快或正确的方法,请告诉我。

You need to split this into two parts.你需要把它分成两部分。 Filter and then copy/ paste.过滤然后复制/粘贴。 See below:见下文:

With Sheet3
    .AutoFilterMode = False
    With .Range("F4:F500")
        .AutoFilter Field:=1, Criteria1:="Riveter 01"
        .SpecialCells(xlCellTypeVisible).Copy Destination:=Sheet2.Range("A5")
    End With
End With

to remove the filter:删除过滤器:

On Error Resume Next
    Sheet3.ShowAllData
On Error GoTo 0

On Error Resume Next is for when there is no filter present to skip the error. On Error Resume Next 适用于没有过滤器可以跳过错误的情况。 Please note the use of Sheet3 and Sheet2 for those looking for a generic solution.请注意 Sheet3 和 Sheet2 对于那些寻找通用解决方案的人的使用。

I think that you have to do this in 2 separate steps:我认为您必须分 2 个单独的步骤执行此操作:

  1. filter the data过滤数据
  2. copy the filtered data to another sheet将过滤后的数据复制到另一个工作表

The answer here has an excellent example of how to do this: Autofilter Macro, then copy visible data ONLY and paste to next available row这里的答案有一个很好的例子来说明如何做到这一点:自动过滤宏,然后仅复制可见数据并粘贴到下一个可用行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM