How to make Microsoft Word visible after opening an Excel file in Word VBA

风流意气都作罢 提交于 2021-02-10 19:34:08

问题


I have a VBA Word macro that opens a Word doc, then opens an Excel file, selects a cell reference and finally displays a message using Msgbox. After the Excel file has been opened I am having trouble finding the code to make Word visible so that the user can view the Msgbox message without having to using the task bar to switch from Excel to Word. I tried oWord.Visible = True but VBA gives me an error. Any hints are appreciated.

See the code below:

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

回答1:


Visible is at the Application level. Your oExcel variable gives you the clue. You don't have a variable called oWord.

Edited to add the following code

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

If you are new to VBA then the following should always be used.

  1. In the VBA IDE ensure each module starts with 'Option explicit'

  2. In the VBA IDE ensure that all checkboxes in Tools.Option.Code Settings are ticked



来源:https://stackoverflow.com/questions/53073228/how-to-make-microsoft-word-visible-after-opening-an-excel-file-in-word-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!