Saving a new document in Word Add-In

Add-in Express™ Support Service
That's what is more important than anything else

Saving a new document in Word Add-In
 
Leon H H




Posts: 43
Joined: 2010-04-06
I've done this before but for the heck of me I can't recall how...
I have a RichEditControl on in Custom task pane and use pastes some text in it. Now user want to save this text as a Word document. What I need is that user will be prompted with SaveFileDialog for a name and location of a new .docx file, and the file will be saved without opening it in a new Word instance.
Instead, the following code without prompting to the user and opens this file in another Word instance. And I am not sure if the file is saved anywhere on the HD...

[CODE] string filePath = "MyTranscript.docx";
Word.Document doc = null;
try
{
doc = new Word.Document();
doc.Paragraphs[1].Range.InsertParagraphBefore();
doc.Paragraphs[1].Range.Text = TranscriptResultRichEditCtrl.Text;

doc.SaveAs(filePath, FileFormat: WdSaveFormat.wdFormatDocument);

doc.Saved = true;
}
catch (Exception ex)
{
Log.Verbose(ex);
}
finally
{
if (doc != null)
Marshal.ReleaseComObject(doc);
}
Posted 02 Jan, 2023 00:23:01 Top
Andrei Smolin


Add-in Express team


Posts: 18793
Joined: 2006-05-11
Hello Leon,

You should never set doc.Saved unless you do this on purpose. The code fragment above does save a Word document; you can check this by checking doc.Saved. Also, after saving the document, you can close it to prevent showing it up.

Regards from Poland (GMT+1),

Andrei Smolin
Add-in Express Team Leader
Posted 02 Jan, 2023 09:29:03 Top
Leon H H




Posts: 43
Joined: 2010-04-06
Great, thanks.
But why I am not prompted with SaveFileDialog to supply file location and name? I remember that this functionality is embedded in SaveAs function, or am I incorrect?
Posted 02 Jan, 2023 15:03:27 Top
Andrei Smolin


Add-in Express team


Posts: 18793
Joined: 2006-05-11
You need to use WordApp.FileDialog[]; see https://learn.microsoft.com/en-us/office/vba/api/office.filedialog. Call FileDialog.Show(), let the user specify a file, grab this info and save the document.

Regards from Poland (GMT+1),

Andrei Smolin
Add-in Express Team Leader
Posted 03 Jan, 2023 06:28:02 Top