Friday, June 15, 2018

Use VBA to work with Microsoft Publisher

First, set a reference to the Microsoft Publisher Object Library in the VBA editor.

Create Publisher object variables:
    Dim pubApp As Publisher.Application
    Dim pubDoc As Publisher.Document

Open a Publisher document to use as a template:    
    Set pubApp = CreateObject("Publisher.Application")
    Set pubDoc = pubApp.Open(FileName:=curPath & "\Templates\" _
    & templateName, ReadOnly:=False, addtorecentfiles:=False, _
    savechanges:=pbDoNotSaveChanges)

Find and replace text in Publisher:
Private Sub replaceText(match As String, replace As String, ByRef pubDoc As Publisher.Document)
    With pubDoc.Find
    .Clear
    .FindText = match
    .ReplaceWithText = replace
    .ReplaceScope = pbReplaceScopeOne
    .Execute
    End With
End Sub

Call replaceText("<<Street>>", theStreet, pubDoc)

Add a table to a Publisher document:
pubDoc.Pages(1).Shapes.AddTable(NumRows:=5, _ NumColumns:=5, Left:=72, Top:=300, Width:=400, Height:=100) .Table.Columns(3).Cells(3).Fill.ForeColor.RGB = RGB _ (Red:=255, Green:=0, Blue:=0)

Add, format and populate rows in a Publisher table:    
Dim rowNew as Row
    Set rowNew = pubDoc.Pages(1).Shapes(1).Table.Rows.Add
    rowNew.Cells(1).TextRange.Font.Name = "Montserrat"
    rowNew.Cells(1).TextRange.Font.Size = 9
    rowNew.Cells(1).TextRange.Text = someValue

Save the Publisher document as a PDF:    
    pubDoc.ExportAsFixedFormat pbFixedFormatTypePDF, _
    docPathAndName, pbIntentStandard, False

Clean up Publisher objects:
    pubDoc.Close
    pubApp.Quit
    Set pubApp = Nothing

No comments:

Post a Comment