【问题标题】:Activate Word window from Excel with VBA使用 VBA 从 Excel 激活 Word 窗口
【发布时间】:2013-02-22 04:40:32
【问题描述】:

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

但就我而言,我不知道文档的名称,它应该是最后一个活动的。我希望使用类似的东西

Word.ActiveDocument

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

Application.SendKeys("%{TAB}")

但它也不起作用。有什么提示吗?

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

【问题讨论】:

  • this 可以帮助您更好地了解如何设置对象来控制 excel vba 中的 word (4-6)
  • 您希望实际使用最后一个活动文档还是创建一个新文档?
  • 最后一个文档是从哪里来的?您是否在 Excel 或其他地方运行代码?

标签: vba excel ms-word


【解决方案1】:

您可以使用后期绑定 (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

【讨论】:

  • 很高兴听到。祝你好运!
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 2018-04-19
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多