Excel VBA在保存之前检查过滤器

时间:2017-05-30 09:52:52

标签: excel vba excel-vba private

我有一个共享的工作簿。当多个用户正在处理它时会遇到问题,而一个用户会使用过滤器进行保存。 我正在尝试编写工作簿代码,以防止在存在过滤器时进行保存。

set xact_abort on;
begin tran
    --all your inserts here
commit tran

如果可能的话,我想查看完整的工作簿,但是会为每张工作单解决。当我运行它时,宏只是保存。我把它放在Microsoft Excel对象>本工作簿部分。

3 个答案:

答案 0 :(得分:0)

AutoFilterMode旁边还有FilterMode,在保存解决问题之前,我会在循环中为每张工作表将它们设置为False

答案 1 :(得分:0)

您的给定代码查看是否有名为" sheet1"已启用过滤器。请注意" Sheet1" (第一张纸的默认名称)与" sheet1"。

不同

您可以使用循环查看工作簿中的每个工作表并测试是否有过滤器:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim wsht As Worksheet
    For Each wsht In ThisWorkbook.Worksheets
        If wsht.AutoFilterMode = True Then
            MsgBox "Filters not allowed, remove filters before saving", vbExclamation, "Warning!"
            Cancel = True
            Exit Sub
        End If
    Next wsht
End Sub 

更加用户友好的方法是在保存之前使用此宏删除任何过滤器,同时还提示用户保存工作簿将删除过滤器并询问他们是否希望继续。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim wsht As Worksheet
    For Each wsht In ThisWorkbook.Worksheets
        If wsht.AutoFilterMode = True Then
            MsgboxAnswer = MsgBox("Filters are currently active, saving this workbook will remove them. Do you want to continue?", vbYesNo)
            If MsgboxAnswer = vbYes Then RemoveFilters = True
            Exit For
        End If
    Next wsht

    If RemoveFilters Then
        For Each wsht In ThisWorkbook.Worksheets
            wsht.AutoFilterMode = False
        Next wsht
    End If
End Sub

答案 2 :(得分:0)

将此代码放在ThisWorkbook Module上,这将清除所有工作表上应用的所有过滤器。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim ws As Worksheet
For Each ws In Worksheets
    If ws.FilterMode Then ws.ShowAllData
Next ws
End Sub