VBA Code to Open Word Template and create new document per list of names

IGPOD

New Member
Joined
May 16, 2014
Messages
20
Hello,

I have somewhat of an advanced question... I have a long list of names in a column in excel (range name, "Names"), what I want to do is create a code that I can run that will open a template (named "CART") and based on the list of names the code would open a copy of the template and input the name into a designated spot.

My issue is I don't know where to start and integrating Word with excel VBA is new to me. Any advise or direction or code I can use as a starting point would be amazing. I'm still a beginner so thank you in advance for your help.

-IGPOD
 

Attachments

  • Thanks.png
    Thanks.png
    15.8 KB · Views: 14

Excel Facts

Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
Hi IGPOD,

You'll need a bookmark in your Word document that code can populate with the names from your Excel file. Have a look at this thread that I solved by in January 2021 which has most of the code you'll need. Let me know if you have trouble adapting it to your needs.

Regards,

Robert
 
Upvote 0
In case anyone reads this I thought I'd write the code to do the job to make things easier:

VBA Code:
Option Explicit
Sub PopulateWordFromExcel()

    Dim strWordDocPath As String, strWordDocName As String, strWordDocDir  As String, strBkMark As String
    Dim objWordApp As Object, objWordDoc As Object, objWordBkm As Object, objWordBkmRange As Object
    Dim rngCell As Range

    'Check if Word is already opened
    On Error Resume Next
        Set objWordApp = GetObject(, "Word.Application")
        If Err.Number <> 0 Then
            'If it isn't, open a new instance of it
            Set objWordApp = CreateObject("Word.Application")
        End If
    On Error GoTo 0
 
    'Assums full path (directory + filename) of the Word document is in a named range called 'WordPath'. Change to suit.
    On Error Resume Next
        strWordDocPath = ThisWorkbook.Names(CStr("WordPath")).RefersToRange.Value
        If Len(strWordDocPath) = 0 Then
            strWordDocPath = Range(CStr("WordPath")).Value
        End If
    On Error GoTo 0
 
    strWordDocName = Replace(strWordDocPath, Left(strWordDocPath, InStrRev(strWordDocPath, Application.PathSeparator)), "")
    strWordDocDir = Left(strWordDocPath, InStrRev(strWordDocPath, Application.PathSeparator))
   
    Select Case FileStatus(strWordDocPath)
        Case Is = 53 'Invalid filename
            MsgBox "The entered file name..." & vbNewLine & """" & strWordDocName & """" & vbNewLine & "...is invalid." & vbNewLine & "Please check and try again.", vbExclamation, "Populate Word from Excel"
            Set objWordApp = Nothing 'Release object from memory
            Exit Sub
        Case Is = 70 'File is open
            MsgBox "The document..." & vbNewLine & """" & strWordDocName & """" & vbNewLine & "...is currently open." & vbNewLine & "Please close it and try again.", vbExclamation, "Populate Word from Excel"
            Set objWordApp = Nothing 'Release object from memory
            Exit Sub
        Case Is = 76 'Invalid path
            MsgBox "The entered directory path..." & vbNewLine & """" & strWordDocDir & """" & vbNewLine & "...is invalid." & vbNewLine & "Please check and try again.", vbExclamation, "Populate Word from Excel"
            Set objWordApp = Nothing 'Release object from memory
            Exit Sub
    End Select
 
    Application.ScreenUpdating = False
 
    'Ensure the Word instance the document is in visible
    objWordApp.Visible = True
   
    strBkMark = "ClientName" 'Word document bookmark name. Change to suit.
   
    For Each rngCell In ThisWorkbook.Names("Names").RefersToRange
        Set objWordDoc = objWordApp.Documents.Open(strWordDocPath)
        Set objWordBkm = objWordDoc.Bookmarks(strBkMark)
        objWordApp.Selection.GoTo What:=-1, Name:=objWordBkm.Name '-1 = wdGoToBookmark
        Set objWordBkmRange = objWordBkm.Range
        objWordBkmRange.Text = Replace(objWordBkmRange.Text, objWordBkmRange.Text, rngCell.Text)
        With objWordDoc
            .Bookmarks.Add strBkMark, objWordBkmRange
            .Close -1 '-1 = wdSaveChanges (no prompt)
        End With
        'I could not get SaveAs2 in Word not to display the File Save dialog so I coded the following as an alternative
        FileCopy strWordDocDir & strWordDocName, strWordDocDir & rngCell.Text & ".docx"
        Set objWordDoc = Nothing
    Next rngCell
 
    Set objWordApp = Nothing 'Release object from memory
   
    Application.ScreenUpdating = True
 
    MsgBox "Excel data has been copied across to Word.", vbInformation, "Populate Word from Excel"

End Sub
'http://www.vbaexpress.com/kb/getarticle.php?kb_id=468
Function FileStatus(strFileName As String) As Long

    Dim lngFileNum As Long
    Dim lngErr     As Long
  
    On Error Resume Next
        lngFileNum = FreeFile()
        Open strFileName For Input Lock Read As #lngFileNum
        Close lngFileNum
        FileStatus = Err
    On Error GoTo 0
  
End Function

I couldn't get the Word document to save as the client name using SaveAs2 without the File Dialog opening so used the FileCopy function to do the same. I'd been keen to see if it is possible if anyone reading this knows how.

Regards,

Robert
 
Upvote 0
@Trebor76 , thank you for your hard work on this, it's obvious you know what you're doing, I'll have to be honest. I'm so out of practice with this and your code is far more advanced than my knowledge. With that said, If you can alter the code to show me how this information is referenced I believe I can fill in the rest. I just don't know what I don't know.

The template is on my desktop entitled "CART.dotx", the named range in my spreadsheet is "Names" the bookmark ID that I put in the template is "Name"; currently I have 37 names, but quarterly that may change and I'll reference the entire group of names needed as "Names" ... As you can imagine this takes a significant amount of time and this would help me tons.
 
Upvote 0
Just need the following tweaks to get things working (hopefully :))

The template is on my desktop entitled "CART.dotx"
Create a named range called WordPath from the cell that houses the full path (directory + filename eg "C:\Users\IGPOD\Desktop\CART.docx").

the bookmark ID that I put in the template is "Name"
Change this line of code...
VBA Code:
strBkMark = "ClientName" 'Word document bookmark name. Change to suit.
...to this:
VBA Code:
strBkMark = "Name" 'Word document bookmark name.

Robert
 
Upvote 0
Create a named range called WordPath from the cell that houses the full path (directory + filename eg

So, I placed the text of the path in the cell and named the range "WordPath", the debugger is locked up on this part: FileStatus
 

Attachments

  • error.png
    error.png
    48.9 KB · Views: 14
Upvote 0
Did you copy in the FileStatus function as well as the code?
 
Upvote 0
Did you copy in the FileStatus function as well as the code?
Yes, I added it just now and it ran without the debugger, however, each Word Doc is blank, none of the info ported over but each sheet was created and named.... they were placed in the Custom Office Templates folder. There was actually no document (all grayed out; like a blank screen)
 
Upvote 0
Not sure what's happening as it worked for me :confused:

they were placed in the Custom Office Templates folder
Correct. They can be saved wherever I just coded it that way.
There was actually no document (all grayed out; like a blank screen)
Try convertting the document from .dotx to .docx via SaveAs and try again.
 
Upvote 0

Forum statistics

Threads
1,214,873
Messages
6,122,029
Members
449,061
Latest member
TheRealJoaquin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top