首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >打开Word文档并带到前线

打开Word文档并带到前线
EN

Stack Overflow用户
提问于 2014-08-18 11:46:14
回答 9查看 29.9K关注 0票数 7

下面是打开Microsoft文档的工作代码片段,然后转到目录中的特定索引。filePath是文件路径,strTopic是链接到Word文档中目录的值。

代码语言:javascript
复制
Set objWord = CreateObject("Word.Application")
objWord.Visible = True

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

docWord.Bookmarks(strTopic).Range.Select

我需要把单词文档放在最前面。

VBA中是否有toFront()类型的“函数”?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2014-08-18 11:58:14

您可以使用APIS实现您想要的结果。我使用两个APIs SetForegroundWindowFindWindow

代码语言:javascript
复制
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应用程序打开,那么您也可以使用以下内容:)

代码语言:javascript
复制
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
票数 11
EN

Stack Overflow用户

发布于 2014-08-18 11:51:59

怎么样,

代码语言:javascript
复制
docWord.Activate

这将使docWord对象的“设置”文件变为前台文件。

编辑:在Access上测试这个,在Excel上测试不可靠。如果Word应用程序有多个实例正在运行,那么使用API是最好的方法。

票数 4
EN

Stack Overflow用户

发布于 2016-01-25 12:12:25

一旦打开了一个文档(或者添加了一个文档),就可以从SetForegroundWindow对象(例如obWord.ActivieWindow.Hwnd)获得一个Hwnd来传递给Hwnd API函数。这样你就不需要在前面搜索正确的单词实例了。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25362563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档