Visio VBA Cheat Sheet
1. Getting Started
Dim app As Visio.Application
Dim doc As Visio.Document
Dim page As Visio.Page
Dim shp As Visio.Shape
Set app = Visio.Application
Set doc = app.ActiveDocument
Set page = app.ActivePage
2. Documents and Pages
'Create a new document
Set doc = app.Documents.Add("")
'Get specific page
Set page = doc.Pages("Page-1")
'Add a new page
Set page = doc.Pages.Add
page.Name = "MyPage"
3. Shapes
'Drop a shape from a stencil
Dim stencil As Visio.Document
Set stencil = app.Documents.OpenEx("BASIC_U.VSSX", visOpenHidden)
Set shp = page.Drop(stencil.Masters("Rectangle"), 3, 3)
'Set shape text
shp.Text = "Hello Visio"
'Move shape
shp.Cells("PinX").FormulaU = "5"
shp.Cells("PinY").FormulaU = "4"
4. Connectors and Glue
'Drop connector
Dim connector As Visio.Shape
Set connector = page.Drop(app.ConnectorToolDataObject, 0, 0)
'Glue to shapes
connector.Cells("BeginX").GlueTo shp1.Cells("PinX")
connector.Cells("EndX").GlueTo shp2.Cells("PinX"
5. Shape Properties
'Resize shape
shp.Cells("Width").FormulaU = "2"
shp.Cells("Height").FormulaU = "1"
'Change fill color
shp.Cells("FillForegnd").FormulaU = "RGB(255,0,0)"
'Change line color
shp.Cells("LineColor").FormulaU = "RGB(0,0,255)"
'Set custom property
shp.Cells("Prop.MyProp").FormulaU = ""MyValue"
6. Shape Iteration
Dim shp As Visio.Shape
For Each shp In page.Shapes
Debug.Print shp.Name
Next
7. Events
Private Sub Document_DocumentOpened(ByVal doc As IVDocument)
MsgBox "Document Opened: " & doc.Name
End Sub
8. Selection and Layers
'Select all shapes
Dim sel As Visio.Selection
Set sel = app.ActiveWindow.Selection
sel.SelectAll
'Assign shape to layer
Dim lyr As Visio.Layer
Set lyr = page.Layers("MyLayer")
lyr.Add shp, True
9. Export and Print
'Save as PDF
doc.ExportAsFixedFormat visFixedFormatPDF, "C:\MyFile.pdf", _
visDocExIntentPrint, visPrintAll
'Print
doc.PrintOut
10. Useful Constants
visOpenHidden - Opens doc invisibly
visSectionObject - Section for shape props
visConnectedShapesAllNodes - All connected shapes
visFixedFormatPDF - Export as PDF
11. Helper Functions
Function FindShapeByName(pg As Visio.Page, name As String) As Visio.Shape
Dim shp As Visio.Shape
For Each shp In pg.Shapes
If shp.Name = name Then
Set FindShapeByName = shp
Exit Function
End If
Next
Set FindShapeByName = Nothing
End Function