Solved

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

Posted on 2014-04-05
2
1,059 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:Murray Brown
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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:Murray Brown
ID: 39980959
Thanks
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
This Micro Tutorial demonstrates in Microsoft Excel how to consolidate your marketing data by creating an interactive charts using form controls. This creates cool drop-downs for viewers of your chart to choose from.
This Micro Tutorial will demonstrate how to use a scrolling table in Microsoft Excel using the INDEX function.

696 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