使用VBA从Excel激活Word窗口 [英] Activate Word window from Excel with VBA
问题描述
我正在尝试从Excel中访问MS Word的窗口.我找到了访问新的Word文档或特定文档的方法,例如 将文本从Excel中的范围复制到Word文档,
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,
但是对于我来说,我不知道该文档的名称,它应该是最后一个活动的文档.我希望使用类似的东西
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
但没有成功.我还尝试模拟Alt + Tab按键来激活窗口,
but no success. I also tried to simulat Alt+Tab keystroke to activate the window with
Application.SendKeys("%{TAB}")
,但是它也不起作用.有什么提示吗?
but it does not work too. Any hint?
我正在尝试创建一个宏,该宏将仅将图表和一些文本复制到Word中,并对文本进行一些格式化.因此,基本上,我可以使用任何方法来完成此任务. 非常感谢.
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的打开实例( http://support.microsoft.com/kb/245115 )和GetObject
.如果您有多个打开的Word实例,则不能保证会获得其中的任何一个.
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.
获取Word实例将使您可以访问ActiveDocument
或应用程序当前的Selection
.我仍然建议您进行一些错误检查,以确保您拥有想要的东西.
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.
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
这篇关于使用VBA从Excel激活Word窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!