使用VBA从Excel激活Word窗口

时间:2013-02-21 15:16:07

标签: vba excel-vba ms-word excel

我正在尝试从Excel访问MS Word的窗口。我找到了访问新Word文档或特定文档的方法,例如 Copy Text from Range in Excel into Word Document

但在我的情况下,我不知道文件的名称,它应该是最后一个活动的名称。我希望使用像

这样的东西
Word.ActiveDocument

但没有成功。我还试图模拟Alt + Tab击键以激活窗口

Application.SendKeys("%{TAB}")

但它也不起作用。任何提示?

我正在尝试创建一个宏,它只是将图表和一些文本复制到Word中,并对其进行一些格式化。所以基本上我可以使用任何方法来完成这项任务。 非常感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用后期绑定(http://support.microsoft.com/kb/245115)和GetObject来访问Word的打开实例。如果您打开了多个Word实例,则无法保证可以特别获取其中任何一个。

获取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