![](/img/trans.png)
[英]MS Word vba to save .docm to .docx WITHOUT converting active document
[英]Word VBA force save as .docm
我最終清理了整個公司使用的 Word 文檔上的某人的爛攤子。 它是一個需要單獨保存為.docm
的宏文件。 我擔心它會“另存為”-d 作為.docm
以外的其他.docm
,但我似乎無法找到一種方法來限制另存為文件選擇器或在仍使用 VBA 的同時在保存時換出擴展名.
我怎樣才能做到這一點?
編輯:我嘗試過的一些事情,但無濟於事:這是正確的想法,但實際上並沒有限制保存https://answers.microsoft.com/en-us/msoffice/forum/ msoffice_word-mso_other/how-to-set-path-for-wddialogfilesaveas-dialog/535b7f9c-9972-425c-8483-35387a97d61d
在底部,微軟表示 SaveAs 與 filter.clear 和 filter.add 不兼容https://msdn.microsoft.com/en-us/library/office/aa219834(v=office.11).aspx
為了劫持 Word 中的本機“另存為”對話框,您需要利用DocumentBeforeSave
的應用程序級事件,然后手動調用 FileDialog,以驗證擴展名。
modEventHandler
。 將以下代碼放入其中。Option Explicit
Public TrapFlag As Boolean
Public cWordObject As New cEventClass
'You may not need these in a DOCM, but I needed to implement this in an ADD-IN
Sub TrapEvents()
If TrapFlag Then
Exit Sub
End If
Set cWordObject.DOCEvent = Application
TrapFlag = True
End Sub
Sub ReleaseTrap()
If TrapFlag Then
Set cWordObject.DOCEvent = Nothing
Set cWordObject = Nothing
TrapFlag = False
End If
End Sub
cEventClass
的類模塊並將此代碼放入模塊中:Option Explicit
Public WithEvents DOCEvent As Application
Private Sub DOCEvent_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
' Do not prevent SAVEAS for *other* documents
If ObjPtr(Doc) <> ObjPtr(ThisDocument) Then
Exit Sub
End If
If SaveAsUI Then
' The user has invoked SAVE AS command , so we will hijack this and use our own FileDialog
Call CustomSaveAs(Doc)
' Prevent duplicate appearance of the SAVEAS FileDialog
Cancel = True
End If
End Sub
Private Sub CustomSaveAs(ByRef Doc As Document)
Dim fd As FileDialog
Dim filename$
Set fd = Application.FileDialog(msoFileDialogSaveAs)
fd.Show
If fd.SelectedItems.Count = 0 Then Exit Sub
filename = fd.SelectedItems(1)
If Not Right(filename, 4) = "docm" Then
' ### DO NOT EXECUTE this dialog unless it matches our .DOCM file extension
MsgBox "This document should only be saved as a DOCM / Macro-Enabled Document", vbCritical, "NOT SAVED!"
Else
fd.Execute
End If
End Sub
ThisDocument
模塊中,執行以下代碼:Private Sub Document_Close()
Call modEventHandler.ReleaseTrap
End Sub
Private Sub Document_Open()
Call modEventHandler.TrapEvents
End Sub
ThisDocument
引發Document_Open
事件,該事件調用TrapEvents
過程。
TrapEvents
過程創建Word.Application
類的WithEvents
實例,向自動化公開其他事件。 其中之一是DocumentBeforeSave
。
我們使用DocumentBeforeSave
事件來捕獲SaveAs
操作。 如果用戶請求了SaveAs
,那么我們將使用在CustomSaveAs
過程中創建的邏輯強制對話框。 這使用簡單的邏輯來測試提供的文件擴展名,並防止文檔不是 DOCM 擴展名時被保存。 如果 FileDialog 確實收到了有效的 DOCM 擴展名,那么我們Execute
將文件保存為新名稱的對話框。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.