Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试从excel vba保存word文件,而不过度写入任何现有文件_Vba_Excel_Ms Word - Fatal编程技术网

尝试从excel vba保存word文件,而不过度写入任何现有文件

尝试从excel vba保存word文件,而不过度写入任何现有文件,vba,excel,ms-word,Vba,Excel,Ms Word,尝试从excel vba保存word文件,而不过度写入任何现有文件。选择的文件名(取自电子表格)可能是重复的,在这种情况下,我希望暂停或停止代码,但它会自动重写,如下所示,尽管我的两个错误捕获尝试失败,word文档被重写: Sub automateword() Dim fileToOpen As String Dim intChoice As Integer Dim myFile As Object mysheet = Acti

尝试从excel vba保存word文件,而不过度写入任何现有文件。选择的文件名(取自电子表格)可能是重复的,在这种情况下,我希望暂停或停止代码,但它会自动重写,如下所示,尽管我的两个错误捕获尝试失败,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
Sub-automateword()
Dim fileToOpen As String
选择整数
将myFile设置为对象
mysheet=ActiveWorkbook.Name
Set Wst=工作簿(mysheet).ActiveSheet
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect=False
'使文件对话框对用户可见
intChoice=Application.FileDialog(msoFileDialogOpen.Show)
如果选择0,那么
'获取用户选择的文件路径
fileToOpen=Application.FileDialog(_
msoFileDialogOpen)。选择编辑项(1)
如果结束
设置wordapp=CreateObject(“word.Application”)
设置myFile=wordapp.documents.Add(fileToOpen)
i=1
直到空为止(Wst单元(i,2))
i=i+1
环
i=i-1
可见=True
Filename=Wst.Cells(i,2)+“”+Wst.Cells(i,3)+Str(Wst.Cells(i,10))
错误转到错误行
wordapp.DisplayAlerts=True
FullPath=“\\networkpath\”和Filename&“.doc”
myFile.SaveAs(完整路径)
出口接头
错误行:
MsgBox(“文件名错误”)
端接头

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


如果Dir(fileToOpen)”,则退出Sub

Document.SaveAs将覆盖现有文件而不会出现提示或错误。您必须首先检查文件是否存在。最好的错误处理策略是首先避免出现运行时错误。在使用文件名之前,请使用
Dir
验证文件是否存在。