Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2014-04-05
2
Medium Priority
?
1,087 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 2000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

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 article describes a serious pitfall that can happen when deleting shapes using VBA.
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
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.

618 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