[GIS] Convert .mxd with embedded VBA command button to ArcMap 10

arcgis-10.0arcmappython

I'm trying to convert an .mxd file from an older version to ArcMap 10. The old version had two simple VBA scripts attached to toolbar buttons. I am trying to convert this .mxd to ArcMap 10. For deployment reasons I would like to maintain everything in a single file. I would also like to continue using toolbar buttons to run the scripts.

I thought all I would have to do is convert the VBA code to Python. It's apparently not that simple. Can someone please explain whether the following is possible in ArcMap 10 (seems like it should be since it was simple in previous versions):

  • single .mxd (no extra .tbx or .py files)
  • two custom toolbar buttons
  • click button1 and it runs some_python_function_1
  • click button2 and it runs some_python_function_2

Best Answer

Several things to do to access ArcObjects via Python

  1. Download comtypes module from http://sourceforge.net/projects/comtypes/files/
  2. Save the following code to a python file (gis.py). Be sure that your pythonpath reads the directory in which you save this file.

.

 def GetCurrentApp():
    """Gets an IApplication handle to the current app.
    Must be run inside the app's Python window.
    Execute GetDesktopModules() first"""
    import comtypes.gen.esriFramework as esriFramework
    return NewObj(esriFramework.AppRef, esriFramework.IApplication)


def CType(obj, interface):
    """Casts obj to interface and returns comtypes POINTER or None"""
    try:
        newobj = obj.QueryInterface(interface)
        return newobj
    except:
        return None

now start programming with python:

import gis as gis
import comtypes.gen.esriArcMapUI as esriArcMapUI
import comtypes.gen.esriCartoas as esriCarto

pApp = gis.GetCurrentApp()

pDoc = pApp.Document
pMxDoc = gis.CType(pDoc, esriArcMapUI.IMxDocument)
pMap = pMxDoc.FocusMap
print str(pMap.Name)
pLayout = pMxDoc.PageLayout
pActiveView = gis.CType(pLayout, esriCarto.IActiveView)
pActiveView.Refresh()

It took me a bit of time to figure this out. It should be noted that I found the following websites very informative:

I hope this helps.

Related Question