Link to home
Start Free TrialLog in
Avatar of Bryce Bassett
Bryce BassettFlag for United States of America

asked on

Trouble in VBA bringing Word document window to top using APIs

In a Word VBA macro, at at one point I create a new document from the user's chosen template, and fill in some fields (via a called subroutine).  Those subroutines interact with the ActiveDoument just fine, but when they are finished, the newly created document is NOT the active window.  It remains hidden behind the default blank document until I manually select it.

Newdoc gets created, and populated with data, but is not the active document when my macro finishes.  Newdoc.activate does nothing, nor does newdoc.select.  I've tried a bunch of APIs, but nothing seems to be working.

What am I doing wrong?  I've checked and newdocname and hWnd have correct values.
Private Sub CommandButton2_Click()  'OK

Dim mytemp As String
Dim newdoc As Document
Dim newdocname As String
dim whichdoc as string

#If VBA7 Then
    Dim hWnd As LongPtr
#Else
    Dim hWnd As Long
#End If

whichdoc = Me.ListBox1.List(Me.ListBox1.ListIndex)
mytemp = contentlibraryfolder & "\Contract Documents\" & whichdoc & ".dotm"
Set newdoc = Application.Documents.Add(Template:=mytemp)

newdoc.Activate

If InStr(whichdoc, "G704") Then  Call fillG704 
  ElseIf InStr(whichdoc, "G714") Then  Call fillG714 
  ElseIf InStr(whichdoc, "G710") Then  Call fillG710 
  ElseIf InStr(whichdoc, "G701") Then  Call fillG701 
End If

newdocname = newdoc.Name
hWnd = FindWindow(vbNullString, newdocname & " - Word")
If hWnd > 0 Then BringWindowToTop(hWnd)
'If hWnd > 0 Then SetForegroundWindow(hWnd)

newdoc.Select
Selection.HomeKey unit:=wdStory

Unload Me

End Sub


Sub fillG714()  'sample

ActiveDocument.Fields(1).Result.Text = "Hello"
ActiveDocument.Fields(4).Result.Text = "World"
ActiveDocument.Fields(36).Result.Text = Date

End Sub

Open in new window

Avatar of Norie
Norie

Have you tried AppActivate?

AppActivate newdoc.Name

Open in new window

Can you share the rest of the code that supports this, like the declarations for BringWindowToTop(), SetForegroundWindow() and FindWindow().  And anything else that this code needs...

Also, what version of Office are you running, and is it 32 or 64 bit?


»bp
ASKER CERTIFIED SOLUTION
Avatar of Bryce Bassett
Bryce Bassett
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial