Vba 保存时提示替换文件
下面是我想做的-Vba 保存时提示替换文件,vba,excel,ms-word,Vba,Excel,Ms Word,下面是我想做的- 从现有工作簿复制数据,并将其作为文本粘贴到保存在本地驱动器上的现有word文件中 使用excel单元格中定义的预定义文本+值+今天的日期保存该文件 这一切都很好,但我面临的唯一问题是,如果文件名已经存在,我希望它能给我一个提示,这样我就可以在知情的情况下决定是否用现有的文件名替换它。但它不能做到这一点。它只是覆盖了现有的一个 代码 Sub GenerateLabelandInvoice() 'Open an existing Word Document from Exc
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
将文件名保存在变量中,然后使用
DIR
测试文件是否存在
这就是你想要的吗?(未经测试)
Dim NewFileName作为字符串
Dim-Ret作为变体
NewFileName=“D:\path name\”和“地址标签和发票-”和_
范围(“L23”)。值&“_
格式(日期,“dd-mmm-yyyy”)和“.docx”
如果Dir(NewFileName)“,则
Ret=MsgBox(“文件存在,是否替换”,vbOKCancel)
如果Ret=vbOK,则
objWord.ActiveDocument.SaveAs文件名:=新文件名_
FileFormat:=wdFormatXMLDocument,AddtoRecentFiles:=False
如果结束
其他的
objWord.ActiveDocument.SaveAs文件名:=新文件名_
FileFormat:=wdFormatXMLDocument,AddtoRecentFiles:=False
如果结束
Hi Sid,感谢您的快速响应。我是否应该在obj.activedocument.saveas代码行之前复制此代码…您可能需要刷新页面。我做了一些编辑!!很好用。但我的意图没有什么不同。我想要一个“弹出窗口”,要求您替换文件、取消或比较两个文件的信息。可能吗?有时候,我希望保留这两个文件,而不是覆盖。如果没有,我想,这段代码对我来说绝对有效。您可以在复制文件时获得该选项,而不是在尝试覆盖文件时。我们可以通过将文件保存到临时目录,然后尝试复制以获得该选项:)
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