尝试保存word文件,从excel vba,而不覆盖任何现有的文件

尝试保存word文件,从excel vba,而不覆盖任何现有的文件。 可能存在的情况是,select的文件名(从电子表格中select)可能是重复的,在这种情况下,我想暂停或停止代码,而是自动重写)如下所示,尽pipe我的两个尝试错误捕获失败,并且Word文档被覆盖:

Sub automateword() Dim fileToOpen As String Dim intChoice As Integer Dim myFile As Object mysheet = ActiveWorkbook.Name Set Wst = Workbooks(mysheet).ActiveSheet Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False 'make the file dialog visible to the user intChoice = Application.FileDialog(msoFileDialogOpen).Show If intChoice <> 0 Then 'get the file path selected by the user fileToOpen = Application.FileDialog( _ msoFileDialogOpen).SelectedItems(1) End If Set wordapp = CreateObject("word.Application") Set myFile = wordapp.documents.Add(fileToOpen) i = 1 Do Until IsEmpty(Wst.Cells(i, 2)) i = i + 1 Loop i = i - 1 wordapp.Visible = True Filename = Wst.Cells(i, 2) + " " + Wst.Cells(i, 3) + Str(Wst.Cells(i, 10)) On Error GoTo errorline wordapp.DisplayAlerts = True FullPath = "\\networkpath\" & Filename & ".doc" myFile.SaveAs (FullPath) Exit Sub errorline: MsgBox ("filename error") End Sub 

在添加word文档之前,您可以添加此if语句。

If Dir(fileToOpen) <> "" Then Exit Sub