打开Word文档并将其放在前面

下面是一个(工作)代码片断,它打开一个Microsoft Word文档,并从目录转到特定的索引。 filePath只是一个文件path, strTopic是一个链接到Word文档中的ToC的值。

 Set objWord = CreateObject("Word.Application") objWord.Visible = True Set docWord = objWord.Documents.Open(fileName:=strPath, ReadOnly:=True) docWord.Bookmarks(strTopic).Range.Select 

但是,我需要将Word文档放在前台。

这是可能的VBA首先? 有没有toFront()types的“函数”我可以使用? AFAIK C#有像app.ActiveWindow.Activate(); 但我不能在vba中获得类似的工作。

你可以使用API​​S来实现你想要的。 我使用两个API SetForegroundWindow和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:\Users\Siddharth Rout\Desktop\Sample.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应用程序,那么您可以使用它以及:)

 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:\Users\Siddharth Rout\Desktop\Sample.docx" Set docWord = objWord.Documents.Open(FileName:=strPath, ReadOnly:=True) hwnd = FindWindow("OpusApp", vbNullString) If hwnd > 0 Then SetForegroundWindow (hwnd) End If End Sub 

怎么样,

 docWord.Activate 

这应该将已经被“设置”为docWord对象的文件前景。

编辑:testing这个访问,安静不可靠的Excel。 如果有多个Word应用程序正在运行,使用API​​是最好的方法。

一旦你打开了一个文档(或者添加了一个文档),就可以得到一个Hwnd从ActiveWindow对象(例如obWord.ActivieWindow.Hwnd)传递给SetForegroundWindow API函数。 这样您就不需要search正确的Word实例。

也可以使用AppActivate“Microsoft Word”

请访问Microsoft帮助: 这里

使用AppActivate需要您想要关注的窗口的确切标题。 例如,对于一个单词2013模板作为“添加”打开,您将不得不使用AppActivate“Document1 – Word”

find了!

 ActiveDocument.Activate 'might not be necessary ActiveDocument.Windows.Application.WindowState = wdWindowStateMaximize 

作品完美无瑕。 我已经有了一个我正在编写的“活动文档”。

http://www.access-programmers.co.uk/forums/showthread.php?t=173871

这似乎每次都有效。 Word是否运行,多个文档是否打开。

 OpenAlready: On Error GoTo 0 With wrdApp .Selection.Goto What:=1, Which:=2, Name:=PageNumber .Visible = True .Activate '<---seems to work well. regardless of number of Word docs open OR not open. End With Set wrdDoc = Nothing Set wrdApp = Nothing