您提供的代碼會查看名爲「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
你有沒有調試過它 - 它是否觸及子系統? – FunThomas