Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

excel - Open Word Document and Bring to Front

Below is a working code snippet that opens a Microsoft Word document, and goes to a specific index from the Table of Contents. filePath is a filepath, and strTopic is a value that links to the Table of Contents in the Word document.

Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Set docWord = objWord.Documents.Open(fileName:=strPath, ReadOnly:=True)

docWord.Bookmarks(strTopic).Range.Select

I need to bring the Word document to the foreground.

Is there a toFront() type "function" in VBA?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve what you want using APIS. I am using two APIs SetForegroundWindow and FindWindow

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

Private Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) _
As Long

Sub Sample()
    Dim objWord As Object, docWord As Object
    Dim strPath As String, FileName As String
    Dim hwnd As Long

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True

    '~~> Change this to the relevant Filename and path
    strPath = "C:UsersSiddharth RoutDesktopSample.docx"
    '~~> Put the acutal file name here without the extension
    FileName = "Sample"

    Set docWord = objWord.Documents.Open(FileName:=strPath, ReadOnly:=True)

    hwnd = FindWindow(vbNullString, FileName & " [Read-Only] - Microsoft Word")

    If hwnd > 0 Then
      SetForegroundWindow (hwnd)
    End If
End Sub

NOTE: If you are sure that there is no other Word Application open other than what you opened then you can use this as well :)

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

Private Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Sub Sample()
    Dim objWord As Object, docWord As Object
    Dim strPath As String
    Dim hwnd As Long

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True

    '~~> Change this to the relevant Filename and path
    strPath = "C:UsersSiddharth RoutDesktopSample.docx"

    Set docWord = objWord.Documents.Open(FileName:=strPath, ReadOnly:=True)

    hwnd = FindWindow("OpusApp", vbNullString)
    If hwnd > 0 Then
      SetForegroundWindow (hwnd)
    End If
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...