【问题标题】:I am getting an error message which i'm unable to debug我收到一条我无法调试的错误消息
【发布时间】:2019-09-10 11:02:50
【问题描述】:

我在运行宏时收到错误代码:

运行时错误 450:参数数量错误或属性分配无效

基本上我只需要过滤 3 个文本 XBKKXBKFXMAI,而我无法使用下面的代码来过滤。

Dim OrigLines, LiveData As Long
Dim FirstRow As Integer

OrigLines = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
FirstRow = 1

    Sheets("Paste_SDR").Select
    Range("$A$1:$FB" & OrigLines).Copy
    Sheets("SDR - working").Select
    Range("A1").Select
    Selection.PasteSpecial
    Rows("1:1").Select
    Application.CutCopyMode = False
    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$FB" & OrigLines).AutoFilter Field:=126, Criteria1:= _
        "<>*XBKK*", Operator:=xlAnd, Criteria2:="<>*XMAI*", Operator:=xlAnd, Criteria2:="<>*XBKF*"

    If Range("A" & Rows.Count).End(xlUp).Row > FirstRow Then
    Range("$A$2:$FB" & OrigLines).SpecialCells(xlCellTypeVisible).Delete Shift:=xlUp
    End If

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    抛出错误是因为您不能多次传递相同的参数。无论如何,按照您尝试的方式将超过 2 个条件传递给自动过滤器是不可能的。

    如果您有要用作过滤器的值列表,请将它们作为数组传递:

    ActiveSheet.Range("$A$1:$FB" & OrigLines).AutoFilter Field:=126, _
        Criteria1:=Array("XBKK", "XBKF", "XMAI"), Operator:=xlFilterValues
    

    更新
    OP 想要删除与这三个值不匹配的所有行。由于没有命令SpecialCells(xlCellTypeInvisible),我看到以下可能

    • 遍历所有行并检查它们是否可见,并将不可见的行收集到一个范围变量中。参见例如https://stackoverflow.com/a/39104356/7599798。使用此范围进行删除。
    • 在 Excel 工作表中创建一个辅助列,其公式为 TRUE 或 FALSE,具体取决于您是否要保留该行。使用 =OR($DV$2="XBKK", DV$2="XBKF", DV$2="XMAI") 之类的东西并将您的过滤器设置为此帮助列

    【讨论】:

    • 嗨,汤姆,感谢您的快速回复。使用您提供的解决方案,正在删除包含“XBKK、XBKF 和 XMAI”的行。我需要保留它们以供以后的步骤使用。
    【解决方案2】:

    我正在提供代码来删除不需要的行。我不使用AutoFilter 方法,但它会快速、精确且易于阅读。

    简而言之,此代码检查每个单元格的指定条件。如果它找到与指定条件不匹配的值,则将它们放在范围对象中。检查完所有单元格后,放置在范围对象中的那些单元格的行将被删除。

    Dim check as Range
    For each check in .Range("DV1:DV" & OrigLines) 'loop through cells to check values against (change column reference if needed
        Select Case check.Value 'interpret the value (text) in the cell
            Case "XBKK", "XMAI","XBKF" 'if any of these values, do nothing
            Case Else 'if another value ....
                 Dim remove as Range
                 If Not remove is Nothing Then 'if remove is already set 
                     Set remove = Union(check, Remove) 'add the cell to the remove range object
                 Else 'if remove is not set (this will only occur on the first cell that matches)
                     Set remove = check 'set the remove range object to the matching cell
                 End IF
        End Select
    Next
    
    If Not remove Is Nothing then remove.EntireRow.Delete 'delete the entire row of every cell in the remove range object
    

    【讨论】:

    • 嗨,Scott,您可以为每一行添加注释吗?
    • 非常感谢 Scott 解释您的代码并帮助我。
    猜你喜欢
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2017-06-27
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2015-10-01
    相关资源
    最近更新 更多