I’m trying to create word documents on the fly in VB.NET, and I’ve found that the documentation on all of this seems very scarce. Right now my program works by looping through a database table, and for each row it pulls out the variables. The program then loops through and parses a template word doc, replacing variables in that template with variables from the database, then saving as a new doc.
Instead, for every “new doc” that I would be creating, I want to just append it onto another doc, that way when it comes time to parse 1000 rows in the table, I don’t have to create and save 1000 different word documents to the filesystem.
I can’t seem to find anything out there about this. Everything mentions merging documents (I actually want to append, not merge) or the only way I can append (“Insert”) a document is by using WordApplication.Selection.InsertFile(newWordDocument.FullName). This works, but requires me to save newWordDocument to the filesystem before inserting it.
Is there a way to, while still in memory, add newWordDocument to my WordApplication object?
Here’s the pseudocode of what I have now
For each row in TableOfVariables
Dim WordApplication as New Word.Application
Dim tempDoc as New Word.Document
tempDoc = WordApplication.Documents.Add
tempDoc = fillVariablesOfTheDocument(tempDoc, row)
tempDoc.Save() 'This is the problem - it saves as a new file rather than appending into WordApplication
Next
Took a while, but somehow I found out about
MailMerge, which I had no idea existed. Long story short, I can have a template document with variables, and I can have an input excel document. The excel document will have a header row which contains the variable names, and each individual cell of the excel doc will represent the variable that will go into the document. When I executeMailMerge, the template will be replaced withnamount of pages (wherenis the number of excel rows). This solves my problem of adding multiple documents to 1 big excel document. I tested this with 1,000 rows in my excel doc, and it worked flawlessly.Here’s the code I ended up with:
Now I just have to tweak it to make it run faster and clean up the UI, but the functionality is completely there.