1

我有一个 VBA Word 宏,它打开一个 Word 文档,然后打开一个 Excel 文件,选择一个单元格引用,最后使用 Msgbox 显示一条消息。打开 Excel 文件后,我无法找到使 Word 可见的代码,以便用户可以查看 Msgbox 消息,而无需使用任务栏从 Excel 切换到 Word。我试过oWord.Visible = True了,但 VBA 给了我一个错误。任何提示表示赞赏。

请看下面的代码:

Sub Module_Test()
Dim oExcel As Object
Dim oWord_Doc as object
Dim wb_open as workbook
Set oExcel = New Excel.Application
str_Excel_Filename = "C:\Test\Excel_Template.xlsx"
Documents.Open ("C:\Test\Doc_to_process.docx")
Set oWord_Doc = activedocument
oExcel.Visible = True
oExcel.ScreenUpdating = True
oExcel.Workbooks.Open str_Excel_Filename
Set wb_open = activeworkbook
wb_open.ActiveSheet.range("a6").Select
' At this point Excel is visible.  But the Msgbox statement below is not visible except when one switches to Word using the task bar.  What statement do I put here to make Word visible?
Msgbox "Here is a message that should be visible when viewing the window containing the Doc_to_process.docx"
End Sub
4

1 回答 1

2

可见是在应用程序级别。您的 oExcel 变量为您提供了线索。您没有名为 oWord 的变量。

编辑添加以下代码

Option Explicit

Sub Module_Test()

Const MY_WB_PATH                As String = "C:\Test\Excel_Template.xlsx"
Const MY_DOC_PATH               As String = "C:\Test\Doc_to_process.docx"

Dim my_xl_app                   As Excel.Application
Dim my_doc                      As Word.Document
Dim my_wb                       As Excel.Workbook

    Set my_xl_app = New Excel.Application

    With my_xl_app
        .Visible = True
        .ScreenUpdating = True
        Set my_wb = .Workbooks.Open(MY_WB_PATH)

    End With

    my_wb.Activate
    my_wb.activeworksheet.Range("a6").Select

    ' At this point Excel is visible.  But the Msgbox statement
    ' below is not visible except when one switches to Word using
    ' the task bar.  What statement do I put here to make Word visible?
    Set my_doc = Documents.Open(MY_DOC_PATH)
    my_doc.Activate
    ' If required
    my_doc.Application.Visible = True

    MsgBox "Here is a message that should be visible when viewing the window containing the Doc_to_process.docx"
End Sub

如果您是 VBA 新手,则应始终使用以下内容。

  1. 在 VBA IDE 中确保每个模块都以“选项显式”开头

  2. 在 VBA IDE 中,确保选中 Tools.Option.Code Settings 中的所有复选框

于 2018-10-30T21:49:56.433 回答