Reputation: 115
I've been trying to save a word document based on this code:
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
However, an error occurs highlighting "wd.SaveAs(Application.StartupPath & "\" & RecipeName & ".docx")" saying that "System.Runtime.InteropServices.COMException: 'Command failed'"
The document never saves. However, when changing the wd.SaveAs path to something simple on my C: drive, it works perfectly fine.
Any help would be greatly appreciateted. Thanks.
Upvotes: 1
Views: 983
Reputation: 35460
After wasting a few hours, trying all sorts of recipes from making document visible/invible to playing with DCOM Config utility, it turned out that I was getting "command failed" for Save command because another part of my code was handling DocumentBeforeSave
event and cancelling save operation by setting ref Cancel
parameter to true
.
Putting it here as a note for myself. Hope this helps someone else too.
Upvotes: 1
Reputation: 13515
It's not apparent from your code where 'RecipeName' comes from. In VBA, you might use code like:
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
passing both RecipeName and RecipeContents (equivalent to your rtxtRecipeContents.Text) to the sub. For example:
Call CreateWordDoc(rtxtRecipeName.Text, rtxtRecipeContents.Text)
As for the Save problem itself, you might not have permission to write to the application's folder. Try replacing:
Application.StartupPath & "\"
with, for example:
"C:\Users\" & Environ("Username") & "\Documents\"
or:
wdApp.Options.DefaultFilePath (wdDocumentsPath) & "\"
Upvotes: 0