How would you focus your ArcMAP application window using VBA?

I have a script that runs and selects polygons and zooms to them, but I would like ArcMap to focus and come to the front at that point.


Dim pDoc As IDocument
Dim pApp As IApplication
Dim pAppROT As IAppROT

Set pAppROT = New AppROT

If pAppROT.Count > 0 Then
Dim p As Integer
Dim x As Integer
p = 0
x = 0
Do While p < pAppROT.Count
If TypeOf pAppROT.Item(p) Is IMxApplication And (pAppROT.Item(p).Document.Title Like "Report.mxd") Then

Set pDoc = pAppROT.Item(p).Document
Set pApp = pDoc.Parent
x = 1
pAppROT.Item(p).Visible = True

End Sub

Set focus = pAppROT.Item(p)

Exit Do

End If

p = p + 1


End If

If x = 0 Then

    Set pDoc = New MxDocument
    Set pApp = pDoc.Parent

    pApp.OpenDocument ("c:\Report.mxd")

    pApp.Visible = True

End If'

1 Answer 1


You can call the Win32 API SetForegroundWindow function as follows:

Option Explicit

Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long

Sub ViewArcMapWindow()
    SetForegroundWindow Application.hwnd
End Sub

However, if you run this directly from the VBA IDE, it may not work as desired since VBA may activate the IDE window when the script finishes.

  • How might i incorporate this into my code? I can't seem to figure out if i call the AppROT funciton or something different. thanks
    – Cody
    Apr 5, 2012 at 15:23
  • Just cast your IMxApplication to IApplication and pass its window handle (.hwnd property) to the SetForegroundWindow function...
    – Petr Krebs
    Apr 5, 2012 at 16:01
  • Inside what application do you run the VBA snippet?
    – Petr Krebs
    Apr 5, 2012 at 16:02
  • I'm running it from a Access 2002 dbase to open arcmap and zoom to a specific polygon. The whole script works just fine, its bringing Arcmap to the front of the display thats catching me. I'll try your solution
    – Cody
    Apr 5, 2012 at 18:23
  • I guess what I am confused mostly about is the syntax and how i might apply it to my code. I have dimensionalized IMxApplications as the IApplication but it still seems to hang/I am having troubles in solving the hwnd piece.
    – Cody
    Apr 5, 2012 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.