获取使用VBA进行保存时显示的“您要覆盖文件”对话框

以下代码保存了我的Excel表格的选定区域。 如果我尝试保存与已存在的文件名称相同的文件,则只保存该文件,而不显示“您要覆盖文件”对话框。

有没有办法改变这个代码,以便它会问我是否想覆盖已有的文件?

Option Explicit Sub CreatePDF() Dim wSheet As Worksheet Dim vFile As Variant Dim sFile As String Set wSheet = ActiveSheet sFile = Replace(Replace(wSheet.Name, " ", ""), ".", "_") _ & "_" _ & Format(Now(), "yyyymmdd\_hhmm") _ & ".pdf" sFile = ThisWorkbook.Path & "\" & sFile vFile = Application.GetSaveAsFilename _ (InitialFileName:=sFile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and FileName to save") If vFile <> "False" Then wSheet.Range("B2:J44").ExportAsFixedFormat _ Type:=xlTypePDF, _ FileName:=vFile, _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False MsgBox "PDF file has been created." End If End Sub 

build议的一种模拟行为的方法是检查选定的SaveAsFilename:

 Option Explicit Sub CreatePDF() Dim wSheet As Worksheet Dim vFile As Variant Dim sFile As String Set wSheet = ActiveSheet sFile = Replace(Replace(wSheet.Name, " ", ""), ".", "_") _ & "_" _ & Format(Now(), "yyyymmdd\_hhmm") _ & ".pdf" sFile = ThisWorkbook.Path & "\" & sFile vFile = Application.GetSaveAsFilename _ (InitialFileName:=sFile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and FileName to save") If Dir(vFile) > vbNullString Then _ If MsgBox("Overwrite File?", _ vbExclamation + vbYesNo, "Overwrite?") = vbNo Then Exit Sub If vFile <> "False" Then wSheet.Range("B2:J44").ExportAsFixedFormat _ Type:=xlTypePDF, _ Filename:=vFile, _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False MsgBox "PDF file has been created." End If End Sub 

另一种select:

更换:

 vFile = Application.GetSaveAsFilename _ (InitialFileName:=sFile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and FileName to save") If vFile <> "False" Then 

通过:

 With Excel.Application.FileDialog(msoFileDialogSaveAs) Dim i As Integer For i = 1 To .Filters.Count If InStr(.Filters(i).Extensions, "pdf") <> 0 Then Exit For Next i .FilterIndex = i .InitialFileName = sFile .Title = "Select Folder and FileName to save" '------------------- Bloc A ------------------------- If CBool(.Show) Then vFile = .SelectedItems.Item(.SelectedItems.Count) End If If vFile <> "" Then '------------------- Bloc A ------------------------- '----------- Or replace "Bloc A" by------------------ 'If Not CBool(.Show) Then Exit Sub 'vFile = .SelectedItems.Item(.SelectedItems.Count) 'And remove the "If vFile <> "False" Then" check '---------------------------------------------------- End With 

如果您select了现有文件,将显示覆盖消息