pythonvbavisiopywin32win32com

Cannot run visio macro using python


I'm trying to run a visio macro using python. I got this so far which doesn't work i get error: AttributeError: <unknown>.Run when calling doc.Application.Run

if os.path.exists("Drawing1.vsdm"):
    visio = win32com.client.Dispatch("Visio.Application")
    visio.Visible = 1
    doc = visio.Documents.Open("Drawing1.vsdm")
    doc.Application.Run("Drawing1.vsdm!test.Read_text_File")

I have seen some examples where people are running excel macros this way

if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"))
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    xl.Application.Save() 
    xl.Application.Quit()
    del xl

Any ideas?


Solution

  • In Visio the Application object doesn't have a Run method, but there is an ExecuteLine method on Document.

    So if your Visio document had a VBA procedure like this:

        Public Sub SayHello(ByVal name As String)
            MsgBox "Hello " & name & "!", vbOKOnly
        End Sub
    

    then the following Python would work:

    doc.ExecuteLine('ThisDocument.SayHello "Bob"')