使用 VBA 从 Excel 激活 Word 窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15005723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Activate Word window from Excel with VBA
提问by Pepacz
I am trying access window of MS Word from Excel. I found methods to access a new Word document or a specific one, like the one at Copy Text from Range in Excel into Word Document,
我正在尝试从 Excel 访问 MS Word 窗口。我找到了访问新 Word 文档或特定文档的方法,例如将 Excel 中的范围内的文本复制到 Word 文档中的方法,
But in my case I do not know the name of the document, it should be the last active one. I was hoping to use something like
但就我而言,我不知道文档的名称,它应该是最后一个活动的。我希望使用类似的东西
Word.ActiveDocument
but no success. I also tried to simulat Alt+Tab keystroke to activate the window with
但没有成功。我还尝试模拟 Alt+Tab 按键来激活窗口
Application.SendKeys("%{TAB}")
but it does not work too. Any hint?
但它也不起作用。任何提示?
I am trying to create a macro that will just copy charts and some text around to Word and do some formating of the text along with it. So basically I can use any approach to this task. Thanks a lot.
我正在尝试创建一个宏,它只会将图表和一些文本复制到 Word 中,并对文本进行一些格式化。所以基本上我可以使用任何方法来完成这项任务。非常感谢。
回答by CuberChase
You can access an open instance of Word by using late binding (http://support.microsoft.com/kb/245115) and GetObject
. If you have multiple instances of Word open you are not guaranteed of getting any one of them in particular though.
您可以使用后期绑定 ( http://support.microsoft.com/kb/245115) 和GetObject
. 如果您打开了多个 Word 实例,则不能保证一定会获得其中的任何一个。
Getting an instance of Word will allow you to access the ActiveDocument
or the Application's current Selection
. I'd still suggest doing some error checking to make sure you've got what you want.
获取 Word 实例将允许您访问ActiveDocument
或应用程序的当前Selection
. 我仍然建议做一些错误检查,以确保你得到了你想要的。
Sub GetWordDocument()
Dim wdApp As Object
'Turn off error handling since if the Application is not found we'll get an error
'Use Late Binding and the GetObject method to find any open instances of Word
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
On Error GoTo 0
'Check to see if we found an instance. If not you can create one if you desire
If wdApp Is Nothing Then
MsgBox "No instances of Word found"
Exit Sub
End If
'Check if there are documents in the found instance of Word
If wdApp.Documents.Count > 0 Then
wdApp.Selection.TypeText "Cool, we got it" & vbCr
'You can now access any of the active document properties too
wdApp.ActiveDocument.Range.InsertAfter "We did indeed"
End If
'Clean up the Object when Finished
Set wdApp = Nothing
End Sub