페이지

2012년 10월 3일 수요일

Create Visio Macro from Visual Studio using Visual Basic

Finally I found a way to write VISIO MACRO from Visual Studio using Visual Basic.
Refer http://support.microsoft.com/kb/303872

        Dim vsoDoc As Microsoft.Office.Interop.Visio.Document
        Dim objPrj As Microsoft.Vbe.Interop.VBProject

        Dim objModule As Microsoft.Vbe.Interop.VBComponent

        Dim CR_LF As String = Chr(10) & Chr(13)

        ' Create a new Visio application
        vsoDoc = Application.Documents.Add("")

        ' Get VB project object
        objPrj = vsoDoc.VBProject

        ' SetVBComponents
        ' If VBComponents is 0, append macros to "ThisDocument"

        objModule = objPrj.VBComponents(0)

        ' Define macro
        strCode = "Private Sub Document_PageChanged(ByVal Page As IVPage)" & CR_LF & _

        "test" & CR_LF & _
        "End Sub"

        ' Write macro to ThisDocument
        objModule.CodeModule.AddFromString(strCode)

        ' SetVBComponents
        ' If VBComponents is not 0, append macros to other module (e.g., Module1)

        objModule = objPrj.VBComponents.Add(VBA.vbext_ComponentType.vbext_ct_Document)


        ' Define macro
        strCode = "sub VBAMacro()" & CR_LF  & _
"   msgbox ""VBA Macro called""" & CR_LF  & _
"end sub"

        ' Write macro to Module1


        objModule.CodeModule.AddFromString(strCode)

P.S When executing above code, I had an error, "Programmatic access to Office VBA project is denied". This error is occurred because Microsoft disables VBA project execution for security purpose. So, to resolve this error, follow guidelines provided by Microsoft.

http://support.microsoft.com/kb/282830






댓글 없음: