打开 Word 文档并置于最前面 [英] Open Word Document and Bring to Front
问题描述
下面是一个工作代码片段,它打开一个 Microsoft Word 文档,并从目录中转到特定索引.filePath
是文件路径,strTopic
是链接到 Word 文档中目录的值.
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
我需要将 Word 文档置于前台.
I need to bring the Word document to the foreground.
VBA 中是否有 toFront()
类型的函数"?
Is there a toFront()
type "function" in VBA?
推荐答案
您可以使用 APIS 实现您想要的.我正在使用两个 API SetForegroundWindow 和 FindWindow
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
注意:如果您确定除了您打开的以外没有其他 Word 应用程序打开,那么您也可以使用它 :)
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
这篇关于打开 Word 文档并置于最前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!