Solved

Excel VBA - Insert data into Word doc and as .pdf

Posted on 2014-04-05
2
1,010 Views
Last Modified: 2014-04-06
Hi
I am using the following Excel VBA code to insert data into a Word template and then create a pdf file from the Word doc.
The process will be used to loop through hundreds of Excel rows and do this for each row
How do I change the code to make sure that the process runs as quickly s possible?


Sub oTest()
     Call FindBMark("inv1", "200", "12 Jan 2014", "Mr Jingles", "School A", "Robbie", "Dave", "082 888 888", "dave@abc.com")
End Sub


Sub FindBMark(ByVal oInvoiceNumber As String, ByVal oInvoiceAmount As String, ByVal oInvoiceDate As String, ByVal oBilledTo As String, _
ByVal oSchool As String, ByVal oChildsName As String, ByVal oGuardian As String, ByVal oContactNumber As String, ByVal oEmailAddress As String)

   
   On Error GoTo EH
   
   Dim MYDOC_DIR As String
   MYDOC_DIR = Environ("userprofile") & "\My Documents"
   Dim TEMPLATE_INVOICE As String
   TEMPLATE_INVOICE = MYDOC_DIR & "\Accounting\Customer_Invoices\"
   Dim EMAIL_PDF As String
   EMAIL_PDF = MYDOC_DIR & "\Accounting\Email_PDF\"
   
   Dim WordObj As Word.Application
   Dim WordDoc As Word.Document

   Dim WordRange As Word.Range
   Set WordObj = CreateObject("Word.Application")
   
   Set WordDoc = WordObj.documents.Open _
       (MYDOC_DIR & "\Accounting\Customer_Invoices\Invoice_Template.dotx")
   WordObj.Visible = True

  'WordObj.ActiveWindow.View.ShowBookmarks = True 'Turn on Bookmarks

   ' Go to the bookmark and insert the value held in a variable at that point
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Invoice_Number")
   WordRange.InsertAfter oInvoiceNumber
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Invoice_Amount")
   WordRange.InsertAfter oInvoiceAmount
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Invoice_Date")
   WordRange.InsertAfter oInvoiceDate
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Billed_To")
   WordRange.InsertAfter oBilledTo
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="School")
   WordRange.InsertAfter oSchool
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Childs_Name")
   WordRange.InsertAfter oChildsName
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Guardian")
   WordRange.InsertAfter oGuardian
      Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Contact_Number")
   WordRange.InsertAfter oContactNumber
   Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Email_Address")
   WordRange.InsertAfter oEmailAddress
   

   ' Uncomment the next line of code to print the document.
   ' WordDoc.PrintOut Background:=False

   ' Uncomment the next line of code to save the modified document.
   ' WordDoc.Save
   
     WordDoc.ExportAsFixedFormat OutputFileName:= _
        EMAIL_PDF & "Doc2.pdf", ExportFormat:=wdExportFormatPDF, _
        OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
        wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
        IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
        wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _
        True, UseISO19005_1:=False

   ' Uncomment the line of code to quit Microsoft Word without

   ' saving changes to the document.
   WordObj.Quit SaveChanges:=wdDoNotSaveChanges
   Set WordObj = Nothing
   Exit Sub
   
EH:
     WordObj.Quit SaveChanges:=wdDoNotSaveChanges
     Set WordObj = Nothing
     Set WordObj = Nothing
     MsgBox Err.Description
     
End Sub
0
Comment
Question by:murbro
2 Comments
 
LVL 26

Accepted Solution

by:
MacroShadow earned 500 total points
Comment Utility
I think this is what you want:
Option Explicit

Dim WordObj As Object
Dim WordDoc As Object

Sub Demo()

    Dim MYDOC_DIR As String
    Dim WordRange As Object

    On Error GoTo EH

    MYDOC_DIR = Environ("userprofile") & "\My Documents"

    Set WordObj = CreateObject("Word.Application")

    WordObj.Visible = True

    Dim i As Integer
    i = 1    ' remove this line if your data doesn't have a header
    For i = 1 To Worksheets("WorksheetName").Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
        Set WordDoc = WordObj.Documents.Open(MYDOC_DIR & "\Accounting\Customer_Invoices\Invoice_Template.dotx")
        Call FindBMark(Range("A" & i).Value, Range("B" & i).Value, Range("C" & i).Value, Range("D" & i).Value, Range("E" & i).Value, Range("F" & i).Value, Range("G" & i).Value, Range("H" & i).Value, Range("I" & i).Value)
        WordDoc.Close
    Next

    ' Uncomment the line of code to quit Microsoft Word without
    ' saving changes to the document.
    WordObj.Quit SaveChanges:=wdDoNotSaveChanges
    Set WordObj = Nothing
    Exit Sub

EH:
    WordObj.Quit SaveChanges:=wdDoNotSaveChanges
    Set WordObj = Nothing
    Set WordObj = Nothing
    MsgBox Err.Description

End Sub

Sub FindBMark(ByVal oInvoiceNumber As String, ByVal oInvoiceAmount As String, ByVal oInvoiceDate As String, ByVal oBilledTo As String, _
              ByVal oSchool As String, ByVal oChildsName As String, ByVal oGuardian As String, ByVal oContactNumber As String, ByVal oEmailAddress As String)


    Dim TEMPLATE_INVOICE As String
    Dim EMAIL_PDF As String
    
    TEMPLATE_INVOICE = MYDOC_DIR & "\Accounting\Customer_Invoices\"
    EMAIL_PDF = MYDOC_DIR & "\Accounting\Email_PDF\"

    'WordObj.ActiveWindow.View.ShowBookmarks = True 'Turn on Bookmarks

    ' Go to the bookmark and insert the value held in a variable at that point
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Invoice_Number")
    WordRange.InsertAfter oInvoiceNumber
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Invoice_Amount")
    WordRange.InsertAfter oInvoiceAmount
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Invoice_Date")
    WordRange.InsertAfter oInvoiceDate
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Billed_To")
    WordRange.InsertAfter oBilledTo
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="School")
    WordRange.InsertAfter oSchool
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Childs_Name")
    WordRange.InsertAfter oChildsName
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Guardian")
    WordRange.InsertAfter oGuardian
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Contact_Number")
    WordRange.InsertAfter oContactNumber
    Set WordRange = WordDoc.GoTo(What:=wdGoToBookmark, Name:="Email_Address")
    WordRange.InsertAfter oEmailAddress

    ' Uncomment the next line of code to print the document.
    ' WordDoc.PrintOut Background:=False

    ' Uncomment the next line of code to save the modified document.
    ' WordDoc.Save

    WordDoc.ExportAsFixedFormat OutputFileName:= _
                                EMAIL_PDF & "Doc2.pdf", ExportFormat:=wdExportFormatPDF, _
                                OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
                                wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
                                IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
                                wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _
                                True, UseISO19005_1:=False

End Sub

Open in new window

0
 

Author Closing Comment

by:murbro
Comment Utility
Thanks
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

How to quickly and accurately populate Word documents with Excel data, charts and images (including Automated Bookmark generation) David Miller (dlmille) Synopsis In this article you’ll learn how to use ExcelToWord! to copy data,charts, shapes …
This tutorial explains how to create a series of drop-down lists that are dependent upon prior selections to guide (“force”) the user to make the correct selection and reduce data errors within Microsoft Excel. Excel 2010 was used for this tutorial;…
Graphs within dashboards are meant to be dynamic, representing data from a period of time that will change each time the dashboard is updated with new data. Rather than update each graph to point to a different set within a static set of data, t…
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now