问题
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.
In the VBA IDE ensure each module starts with 'Option explicit'
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