我一直在尝试根据此代码保存word文档:
Private Sub CreateWordDoc()
Dim wa As Word.Application
Dim wd As Word.Document
Dim wp As Word.Paragraph
wa = CreateObject("Word.Application")
wa.Visible = False
wd = wa.Documents.Add
wp = wd.Content.Paragraphs.Add
wp.Range.Text = rtxtRecipeContents.Text
wd.SaveAs(Application.StartupPath & "\" & RecipeName & ".docx")
wa.Quit()
End Sub
然而,突出显示“wd.SaveAs(Application.StartupPath&amp;”\“&amp; RecipeName&amp;”.docx“)”说“System.Runtime.InteropServices.COMException:'命令失败'”< / p>
该文件永远不会保存。但是,当在我的C:驱动器上将wd.SaveAs路径更改为简单的路径时,它可以正常工作。
任何帮助都会非常感激。感谢。
答案 0 :(得分:0)
从您的代码中可以看出,&#39; RecipeName&#39;来自。在VBA中,您可以使用以下代码:
Private Sub CreateWordDoc(RecipeName As String, RecipeContents As String)
Dim wdApp As New Word.Application, wdDoc As Word.Document
With wdApp
.Visible = False
Set wdDoc = .Documents.Add(Visible:=False)
With wdDoc
.Range.Text = RecipeContents
.SaveAs2 FileName:=Application.StartupPath & "\" & RecipeName & ".docx", _
Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close False
End With
.Quit
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub
将RecipeName和RecipeContents(相当于你的rtxtRecipeContents.Text)传递给sub。例如:
调用CreateWordDoc(rtxtRecipeName.Text,rtxtRecipeContents.Text)
至于Save问题本身,您可能没有权限写入应用程序的文件夹。尝试更换:
Application.StartupPath&amp; &#34; \&#34;
,例如:
&#34; C:\用户\&#34; &安培; Environ(&#34;用户名&#34;)&amp; &#34; \文件\&#34;
或:
wdApp.Options.DefaultFilePath(wdDocumentsPath)&amp; &#34; \&#34;