我最终清理了整个公司使用过的Word文档上的人。这是一个宏观繁重的文档,需要专门保存为.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
答案 0 :(得分:2)
为了劫持本土" SaveAs"在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
过程创建WithEvents
类Word.Application
实例,将其他事件暴露给自动化。其中之一是DocumentBeforeSave
。
我们使用DocumentBeforeSave
事件来捕获SaveAs
操作。如果用户请求了SaveAs
,那么我们强制使用在CustomSaveAs
过程中创建的逻辑对话框。这使用简单的逻辑来测试所提供的文件扩展名,并防止文档在不是DOCM扩展时被保存。如果FileDialog确实收到有效的DOCM扩展,那么我们Execute
将文件保存为新名称的对话框。