我有一个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
答案 0 :(得分: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,则应始终使用以下内容。
在VBA IDE中,确保每个模块均以“显式选项”开头
在VBA IDE中,确保选中了Tools.Option.Code Settings中的所有复选框