自动过滤然后从表中删除行(如果有)
我已经录制了宏来自动过滤并从表中删除行。这不是动态的,因为如果给定表中不存在过滤条件,则宏将中断。
我正在尝试自动过滤并删除行(如果有)。我正在尝试遵循这篇文章。
我的代码没有返回任何错误,但也没有执行任何操作。我添加了消息框以确保它正在运行。
到目前为止,这是我的代码:
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
I've recorded macros to autofilter and delete rows from a table. This is not dynamic in the sense that if the filter criteria does not exist in a given table then the macro will break.
I am trying to autofilter and delete the rows if any. I am trying to follow this post.
My code returns no errors, but also does not do anything. I added the message box to make sure that it was running.
Here is my code so far:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除 Excel 表格中筛选的行
Delete Filtered Rows in an Excel Table
我不知道这是一个错误还是一个功能,但 .AutoFilterMode 似乎在 Excel 2013 或更高版本中始终返回 False。我看到的所有使用 .AutoFilterMode 的示例都早于此。
我认为替换是列表对象上的 .ShowAutoFilter 。在您的代码中,lo.ShowAutoFilter 应返回 True 或 False,具体取决于是否设置了自动筛选器。
但你的其余代码似乎也有问题。测试
如果 lo.Parent.autofilter.Filters(7).Criteria1 = "APGFORK" 则
抛出错误并删除自动过滤器。
I don't know if it is a bug or a feature, but .AutoFilterMode seems to returns False all the time in Excel 2013 or later. All examples I see that use .AutoFilterMode are earlier than that.
I think the replacement is .ShowAutoFilter on the listobject. In your code, lo.ShowAutoFilter should return True or False depending on whether or not the autofilter is set or not.
But the rest of your code seems problematic too. The test
If lo.Parent.autofilter.Filters(7).Criteria1 = "APGFORK" Then
throws an error and removes the autofilter.
我最终采取了不同的方法:
这样,如果数据集中不存在“APGFORK”,它将继续前进而不会出现错误代码。
I Ended up taking a different approach:
This way if "APGFORK" does not exist in a data set, it will move on without an error code.
试试这个代码
Try this code