以下是我尝试做的事情 -
代码
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
答案 0 :(得分:1)
将文件名保存在变量中,然后使用DIR
测试文件是否存在。
这是你在尝试什么? (的未测试强>)
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