Microsoft.Office.Interop.Word saveas2并使用vb.net保存获取命令失败

时间:2017-08-16 20:05:45

标签: .net vb.net ms-word

我不断得到" Command Fail"在尝试保存以编程方式创建的新.docx时,在saveas,saveas2或保存调用中。我知道正在创建该文件。离线工作得很好。 Visual Studio 2013 Microsoft.Office.Interop.Word 15 服务器和开发机器上的Microsoft Office 10 测试代码:

myInfo_lbl.Text = ""
Dim word As New Microsoft.Office.Interop.Word.Application
word.Visible = True
Dim doc As Microsoft.Office.Interop.Word.Document
doc = word.Documents.Add()
Try
    Dim insertText As String = "This thing needs to start fn working. Damn it!"
Dim range As Microsoft.Office.Interop.Word.Range = doc.Range(Start:=0, End:=0)
range.Text = insertText
doc.SaveAs2("D:\myCVCOL_Files\test2.doc")
'doc.Save()
'doc.SaveAs2("D:\myCVCOL_Files\test2.doc")
Catch ex As COMException
    myInfo_lbl.Text = ex.ErrorCode & " ~ " & ex.HResult & " ~ " & ex.Message & " ~  try 6"
Finally
    Dim save_changes As Object = False
    doc.Close(save_changes)
    word.Quit(save_changes)
End Try

3 个答案:

答案 0 :(得分:0)

您似乎没有设置格式。试试这段代码

Imports System.Runtime.InteropServices

Module Module1

    Sub Main()
        CreateDoc()
    End Sub

    Public Sub CreateDoc()
        Dim wordApp As New Microsoft.Office.Interop.Word.Application
        Dim wordDoc As Microsoft.Office.Interop.Word.Document
        Dim range As Microsoft.Office.Interop.Word.Range
        Dim fileName As String
        Dim insertText As String

        Dim format As Microsoft.Office.Interop.Word.WdSaveFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument

        wordApp = New Microsoft.Office.Interop.Word.Application()
        wordDoc = New Microsoft.Office.Interop.Word.Document()
        insertText = "Some text"

        wordApp.Visible = True

        fileName = "D:\Projects\Sandbox\StackOverflow\ConsoleVB\test2.doc"

        wordDoc = wordApp.Documents.Add()

        range = wordDoc.Range(Start:=0, End:=0)
        range.Text = insertText

        wordDoc.SaveAs2(fileName, Format)

        wordDoc.Close(Nothing, Nothing, Nothing)
        wordDoc = Nothing
        wordApp = Nothing

    End Sub
End Module

答案 1 :(得分:0)

我发现我在搜索2天的问题的解决方案是Word中的设置。 发现于:https://social.msdn.microsoft.com/Forums/vstudio/en-US/53a0aa18-5f26-4a51-95c8-5c0ff9be28f4/command-failed-at-microsoftofficeinteropworddocumentclasssaveas?forum=vsto

"之前我遇到过这个问题,我用Google搜索了两天,最后我找到了运行命令dcomcnfg.exe或转到组件服务的解决方案然后你必须选择DCOM配置并选择Microsoft Word和获取它的属性并在标识选项卡中选择交互式用户而不是启动用户。"

答案 2 :(得分:0)

在 Windows 10 环境中使用 VB.NET 2013 中的 function SaveAs(WordDocFilePath & WordDocName & ".pdf", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF) 将单词转换为 pdf 时,我有好几个月出现了 80% 的错误。我尝试了很多东西,但这个非常简单的更改解决了所有问题:

WordApp.ScreenUpdating = False(之前是否为真)

相关问题