Solved

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

Posted on 2014-04-05
2
1,029 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 27

Accepted Solution

by:
MacroShadow earned 500 total points
ID: 39980836
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
ID: 39980959
Thanks
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
Some code to ensure data integrity when using macros within Excel. Also included code that helps secure your data within an Excel workbook.
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

786 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