提示在保存时replace文件

下面是我想要做的 –

  1. 复制现有工作簿中的数据,并将其作为文本粘贴到保存在本地驱动器上的现有字符文件中
  2. 使用在excel单元格+今天的date中定义的预定义文本+值保存该文件
  3. 这一切都很好,但只是我面对的问题是,我希望它给我一个提示,如果文件名已经存在,这样我可以作出明智的决定是否取代它与现有的。 但是这并不是这样。 它只是覆盖现有的。

Sub GenerateLabelandInvoice() 'Open an existing Word Document from Excel Dim objWord As Object Set objWord = CreateObject("Word.Application") objWord.Visible = True objWord.Application.DisplayAlerts = True objWord.Documents.Open "D:\path name \ file name.docx" Range("L19:L29").Copy With objWord .Selection.PasteSpecial DataType:=wdPasteText objWord.ActiveDocument.SaveAs Filename:="D:\path name\" & _ "Address Label & Invoice - " & Range("L23").Value & " " & _ Format(Date, "dd-mmm-yyyy") & ".docx", _ FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False objWord.Visible = True objWord.Application.DisplayAlerts = True End With End Sub 

将文件名保存在一个variables中,如果文件存在,则使用DIRtesting。

这是你正在尝试? ( 未经testing

 Dim NewFileName As String Dim Ret As Variant NewFileName = "D:\path name\" & "Address Label & Invoice - " & _ Range("L23").Value & " " & _ Format(Date, "dd-mmm-yyyy") & ".docx" If Dir(NewFileName) <> "" Then Ret = MsgBox("File exists. Would you like to replace", vbOKCancel) If Ret = vbOK Then objWord.ActiveDocument.SaveAs Filename:=NewFileName, _ FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False End If Else objWord.ActiveDocument.SaveAs Filename:=NewFileName, _ FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False End If