gpt4 book ai didi

excel - 如果条件存在,VBA 自动过滤

转载 作者:行者123 更新时间:2023-12-04 20:08:00 25 4
gpt4 key购买 nike

我已经录制了宏来自动过滤和删除表中的行。但这不是动态的,因为如果给定表中不存在过滤条件,则宏将中断。
我正在尝试创建一个代码,如果条件存在或不执行任何操作,它将自动过滤和删除行。我正在尝试关注 this post ,但我错过了一些东西。请帮忙。
我的代码没有返回错误,但也没有做任何事情。我添加了消息框以确保它实际上正在运行。
到目前为止,这是我的代码:

Sub autofilter()

Dim lo As ListObject

Set lo = Worksheets("BPL").ListObjects("Table1")


With Sheets(1)
If .AutoFilterMode = True And .FilterMode = True Then
If lo.Parent.autofilter.Filters(7).Criteria1 = "APGFORK" Then
'
lo.Range.autofilter Field:=7, Criteria1:="APGFORK"

Application.DisplayAlerts = False
lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True

lo.autofilter.ShowAllData
'
End If
End If
End With

MsgBox ("Code Complete")

End Sub

最佳答案

删除 Excel 表中的筛选行

  • 不是整行!

  • Option Explicit

    Sub DeleteFilteredRows()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    Dim tbl As ListObject: Set tbl = wb.Worksheets("BPL").ListObjects("Table1")

    Dim dvrg As Range ' Data Visible Range

    With tbl
    If .ShowAutoFilter Then
    If .Autofilter.FilterMode Then .Autofilter.ShowAllData
    End If
    .Range.Autofilter 7, "APGFORK"
    On Error Resume Next
    Set dvrg = tbl.DataBodyRange.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    .Autofilter.ShowAllData
    End With

    Dim IsSuccess As Boolean

    If Not dvrg Is Nothing Then
    dvrg.Delete xlShiftUp
    IsSuccess = True
    End If

    If IsSuccess Then
    MsgBox "Data deleted.", vbInformation
    Else
    MsgBox "Nothing deleted.", vbExclamation
    End If

    End Sub

    关于excel - 如果条件存在,VBA 自动过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71618194/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com