我希望在将Excel工作表保存为PDF之前对其进行更改,并在创建副本后撤消这些更改。我想过使用Workbook_BeforeSave
事件来实现更改,并考虑使用Workbook_AfterSave
事件将工作表恢复到原始状态。
我遇到的问题是我想确定SaveAs指令的输出格式。它似乎在Workbook_BeforeSave
事件中不可用,并且我知道除非我强制用户使用此对话框的特定实例,否则我不会捕获SaveAs对话框。
我希望用户从Excel的用户界面中选择SaveAs并在他选择保存为PDF时采取措施。
答案 0 :(得分:4)
您可以通过控制msoFileDialogSaveAs
来确定文件路径和扩展名:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim intChoice As Integer
Dim strPath As String
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogSaveAs).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = _
Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
'displays the result in a message box
Call MsgBox(strPath, vbInformation, "Save Path")
End If
SaveAsUI = False
Cancel = True
End Sub
获得完整路径Cancel = True
后,将停止SaveAs操作,以便您可以选择是否保存。
修改:您可以确定用户是否按下了Save
按钮或SaveAs
SaveAsUI
。如果按Save
,则SaveAsUI = False
SaveAs
,然后SaveAsUI = True
编辑2: 这是我如何实现上述内容的一个例子:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'cancel all default actions by excel application
Cancel = True
'if save was selected instead of SaveAs
If (SaveAsUI = False) Then
Cancel = False
'if SaveAs was selected
ElseIf (SaveAsUI = True) Then
SaveAsUI = False
Dim intChoice As Integer
Dim strPath As String
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogSaveAs).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
'get file extention
fileExt = Right(strPath, Len(strPath) - InStr(strPath, ".") + 1)
'if pdf is the chosen format
If (InStr(strPath, "PDF") > 0) Then
'actions with pdf format
Call MsgBox(strPath, vbInformation, "Save Path")
Else
With ActiveWorkbook
'on error resume next in case of extention macro free prompt no is selected
'see example by removing on error resume next and saving extention ".xlsx"
On Error Resume Next
.SaveAs strPath
On Error GoTo 0
End With
End If
End If
End If
End Sub