Create Letters.doc in word with bookmarks in excel

rockdrigotoca

New Member
Joined
Aug 24, 2010
Messages
23
Hi everyone!!

I'm trying to create Word documents from Excel fields.

I already created bookmarks in Word and have the same Titles in A Row in Excel 2003 and I have tried the following threads:

http://www.mrexcel.com/forum/showthread.php?t=451429&highlight=excel+code+word+bookmark
http://www.mrexcel.com/forum/showthread.php?t=428862&highlight=excel+code+word+bookmark

But I cannot manage it properly. I know that I need the code that goes on the lines of Set WdApp = CreateObject("Word.Application")
rather than Set WdApp = New.Object
I cannot get Word to open a document! =(

It's basic letter creation, First_Name, 2_Name, Address_1, Address_2...
These have been bookmarked in Word and have exact same Titles in Columns A-D

Could anyone please help me???
 
Well, as I don't actually want to do everything that this code does, I'd like to know what specific parts do what (e.g., what part populates the bookmarks from the sheet) so I can customize it an eliminate what I don't need.

What I'd like to do is, have elements of a specific, single row populate a template document; then "save as" so I still have my original template.

Hope you can help!
 
Upvote 0

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
Derek,

Actually that is what I have been trying to do but without much success.
On the code, any line that starts with a ' are comments to explain what that part does.
I would suggest you open up a new thread.
I opted to use MailMerge directly from Word (I'm also quite new in Macros and Code.

Good luck!!
 
Upvote 0
The example given earlier does not replace the template but, instead, creates all the documents in one file and then leaves it visible for you to check and save.
To create individual documents all you have to do is add an extra column containing the name of the output file and add/move/delete some code. In the following code example, I was using Column D (colum 4) for the output filename and I actually used a formula to create the filenames using other data (e.g. name) in the same row.
To see what I have moved, added or removed look for the lines containing "<=====".
Code:
Option Explicit
Sub MailMerge()
'Word application objects declaration
' Important:
' Set Reference (Tools menu) to Microsoft Word nn.n Object Library
Dim oApp      As Word.Application
Dim oDoc      As Word.Document
Dim oTemplate As Word.Document
Dim oBookMark As Word.Bookmark
' Excel application objects declaration
Dim strOutputFilename As String ' <===== New line of code
Dim wb As Workbook
Dim ws As Worksheet
Dim wsControl As Worksheet
Dim rng As Range
Dim rng2 As Range
Dim objX As Object
Dim strDocName As String
Dim strPathName As String
Dim lngKount As Long
Dim lngRecordKount As Long
Dim strFileName As String
'
On Error GoTo HandleError

'
     Application.ScreenUpdating = False
     Set wb = ThisWorkbook
     Set ws = wb.Worksheets("Merge Data")
     Set wsControl = wb.Worksheets("Control Sheet")
'Set data range
    ' Records in Column A, excluding heading
     Set rng = ws.Range(ws.Cells(2, 1), ws.Cells(65536, 1).End(xlUp))
     lngRecordKount = rng.Rows.Count
' Get location of WORD document:
     strPathName = wsControl.Range("B1").Value
     strDocName = wsControl.Range("B2").Value
     If ((strDocName = "") Or (strDocName = " ")) Then
        ' use document with same name as this workbook:
         strDocName = Left(wb.Name, Len(wb.Name) - 4) & ".doc"
     End If
     If ((strPathName = "") Or (strPathName = " ")) Then
         ' use same path as this workbook:
         strPathName = wb.Path
     End If
     strFileName = strPathName & "\" & strDocName
' Check that file exists:
     If Dir(strFileName) = "" Then
         MsgBox strFileName & vbCrLf & "cannot be found", vbOKOnly + vbCritical, "Error"
                GoTo HandleExit
    End If
'Create new word application
     Application.StatusBar = "Starting Microsoft Word"
     Set oApp = CreateObject("Word.Application")
'Loop in data range
     lngKount = 1
     For Each rng2 In rng.Cells
         Application.StatusBar = "Creating document " & lngKount & " of " & lngRecordKount
         'Create new document
         'Application.StatusBar = "Creating new Word Document" <===== No longer required
         Set oDoc = oApp.Documents.Add ' <===== moved here
         oApp.Selection.InsertFile strFileName
        'Find all bookmarks and replace with data:
         For Each oBookMark In oDoc.Bookmarks
             'Corresponding header found in first row ?
             Set objX = ws.Rows(1).Find(oBookMark.Name, LookIn:=xlValues, LookAt:=xlWhole)
             If Not objX Is Nothing Then
                ' heading found for bookmark
                 oBookMark.Range.Text = rng2.Offset(, objX.Column - 1).Value
            Else
                 MsgBox "Error - Bookmark '" & oBookMark.Name & "' not found in " & vbCrLf & _
                    "[" & wb.Name & "]!" & wsControl.Name & vbCrLf & vbCrLf & _
                    "Please check that all bookmarks exist as headings", vbOKOnly, "Bookmark Error"
                 oApp.Quit
                 GoTo HandleExit
            End If
        Next oBookMark
        'Goto next page
        'wdPageBreak = 7
         ' oApp.Selection.InsertBreak 7  <===== No longer required
         strOutputFilename = ws.Cells(rng2.Row, 4) ' <===== New line of code
         oDoc.SaveAs (strOutputFilename) ' <===== New line of code
            ' (the "4" refers to column containing the output filename in MY workbook and should be changed)
         oDoc.Close ' <===== New line of code
         lngKount = lngKount + 1
    Next rng2
'
    MsgBox "Process complete - please check result", vbOKOnly + vbInformation, "Merge Complete"
    ' oApp.Visible = True   <===== Not required in the code revision
HandleExit:
     On Error Resume Next
     oApp.Quit ' <===== New line of code
     Application.StatusBar = ""
     Application.ScreenUpdating = True
     Set oDoc = Nothing
     Set oTemplate = Nothing
     Set oBookMark = Nothing
     Set wb = Nothing
     Set ws = Nothing
     Set wsControl = Nothing
     Set rng = Nothing
     Set rng2 = Nothing
     Set objX = Nothing
'
    Set oApp = Nothing
'
    Exit Sub
'
HandleError:
    ' Do something here?
    Resume HandleExit
End Sub
 
Upvote 0
Derek,

I have adapted the code that you provided in the previous post to create a word doc from data in Excel. I am always creating one doc at a time but I've set things up so that it works well and I'm thrilled to have gotten as far as I have with this.

The issue I have is as follows:

I'm trying hard to keep my word doc to three pages. My template fits (barely but perfectly) onto three pages. The text/values from Excel that I'm inserting into Word really aren't any longer than the keywords in Word that they replace (so that's not increasing the length of my document) but still I'm unable to get it to fix onto three pages. The problem is that the line spacing in the newly created doc keeps being Multiple at 1.15. What's weird though is that the templace dicument that I'm using has everything set up for single spacing, as does my Normal.dotm template. So, where is this multiple spacing coming from and can I either prevent it or fix it? I'm trying to fix it after that fact with code like
Code:
Selection.WholeStory
With Selection.ParagraphFormat
.LineSpacingRule = wdLineSpaceSingle
End With
but I've tried about 100 variations of that and can't fix it. The best solution would be to just prevent it from happening in the first place but to fix it afterward would work too. In case it would help I'll post my entire procedure below. You'll find it little changed from your code above (largely because I don't know anything about Word VBA or how to use it in an Excel VBA procedure). Thanks in advance for your time and any ideas you may have.
Code:
Sub MailMerge()
'Word application objects declaration
' Important:
' Set Reference (Tools menu) to Microsoft Word nn.n Object Library
Dim oApp      As Word.Application
Dim oDoc      As Word.Document
Dim oTemplate As Word.Document
Dim oBookMark As Word.Bookmark
' Excel application objects declaration
Dim strOutputFilename As String ' <===== New line of code
Dim wb As Workbook
Dim ALog As Worksheet
Dim wsControl As Worksheet
Dim rng As Range
Dim rng2 As Range
Dim objX As Object
Dim strDocName As String
Dim strPathName As String
Dim lngKount As Long
Dim lngRecordKount As Long
Dim strFileName As String
'
On Error GoTo HandleError
'
     'Application.ScreenUpdating = False
     
     Set wb = ThisWorkbook
     Set ALog = wb.Worksheets("New Master")
     Set wsControl = wb.Worksheets("Control Sheet")
'Set data range
    ' Records in Column A, excluding heading (on Control sheet)
     Set rng = wsControl.Range(wsControl.Cells(2, 1), wsControl.Cells(65536, 1).End(xlUp))
     lngRecordKount = rng.Rows.Count
' Get location of WORD document:
     strPathName = ALog.Range("O1").Value
     strDocName = ALog.Range("O2").Value
     If ((strDocName = "") Or (strDocName = " ")) Then
        ' use document with same name as this workbook:
         strDocName = Left(wb.Name, Len(wb.Name) - 4) & ".doc"
     End If
     If ((strPathName = "") Or (strPathName = " ")) Then
         ' use same path as this workbook:
         strPathName = wb.Path
     End If
     strFileName = strPathName & "\" & strDocName
     
     '********************
' Check that file exists:
     If Dir(strFileName) = "" Then
         MsgBox strFileName & vbCrLf & "cannot be found", vbOKOnly + vbCritical, "Error"
                GoTo HandleExit
    End If
    '********************
    
'Create new word application
     Application.StatusBar = "Starting Microsoft Word"
     Set oApp = CreateObject("Word.Application")
'Loop in data range
     lngKount = 1
     For Each rng2 In rng.Cells
         Application.StatusBar = "Creating document " & lngKount & " of " & lngRecordKount
         'Create new document
         'Application.StatusBar = "Creating new Word Document" <===== No longer required
         Set oDoc = oApp.Documents.Add ' <===== moved here
         oApp.Selection.InsertFile strFileName
        'Find all bookmarks and replace with data:
         For Each oBookMark In oDoc.Bookmarks
             'Corresponding header found in first row ?
             Set objX = wsControl.Rows(1).Find(oBookMark.Name, LookIn:=xlValues, LookAt:=xlWhole)
             If Not objX Is Nothing Then
                ' heading found for bookmark
                 oBookMark.Range.Text = rng2.Offset(, objX.Column - 1).Value
            Else
                 MsgBox "Error - Bookmark '" & oBookMark.Name & "' not found in " & vbCrLf & _
                    "[" & wb.Name & "]!" & wsControl.Name & vbCrLf & vbCrLf & _
                    "Please check that all bookmarks exist as headings", vbOKOnly, "Bookmark Error"
                 oApp.Quit
                 GoTo HandleExit
            End If
        Next oBookMark
        'Goto next page
        'wdPageBreak = 7
         ' oApp.Selection.InsertBreak 7  <===== No longer required
         
         ''''''''''-------> BA: 10 's means that I commented out those lines bc I don't want it to save anything
         ''''''''''strOutputFilename = ALog.Cells(rng2.Row, 4) ' <===== New line of code
         ''''''''''oDoc.SaveAs (strOutputFilename) ' <===== New line of code
            ' (the "4" refers to column containing the output filename in MY workbook and should be changed)
         ''''''''''oDoc.Close ' <===== New line of code
         
         lngKount = lngKount + 1
    Next rng2
'
    'MsgBox "Process complete - please check result", vbOKOnly + vbInformation, "Merge Complete"
     oApp.Visible = True   '<===== Not required in the code revision
    
    
HandleExit:
     On Error Resume Next
     'oApp.Quit ' <===== New line of code...BA: this was giving me a lot of weird stuff when I was trying to close docs
     Application.StatusBar = ""
     Application.ScreenUpdating = True
     Set oDoc = Nothing
     Set oTemplate = Nothing
     Set oBookMark = Nothing
     Set wb = Nothing
     Set ALog = Nothing
     Set wsControl = Nothing
     Set rng = Nothing
     Set rng2 = Nothing
     Set objX = Nothing
'
    Set oApp = Nothing
'
    Exit Sub
'
HandleError:
    ' Do something here?
    Resume HandleExit
    
    
End Sub

Thanks again. I do appreciate you taking the time to look at this.
 
Upvote 0

Forum statistics

Threads
1,224,597
Messages
6,179,808
Members
452,944
Latest member
2558216095

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