[英]Open Excel from VBA in Word
I use Office for Mac and I want to open Excel (and then a document within it) using a macro in Word.我使用 Office for Mac,我想使用 Word 中的宏打开 Excel(然后是其中的文档)。
Dim myexl As Excel.Application '(1)
Dim myworkbook As Workbooks
Dim my_path As String
... ...
Set myexl = CreateObject("Excel.Application") '(2)
Set myworkbook = myexl.Workbooks.Open(my_path) '(3)
However, the line (2) generates "Type mismatch" in the above code.但是,第 (2) 行在上述代码中生成“类型不匹配”。 If I try to switch (1) so that instead it reads
如果我尝试切换 (1) 以使其改为
Dim myexl As Object
then (2) works but now I get "Object doesn't support this property or method" for line (3).然后(2)有效,但现在我得到第(3)行的“对象不支持此属性或方法”。 This is like a catch 22.
这就像一个陷阱 22。
How can I solve this?我该如何解决这个问题? I want to open Excel and still be able to use the methods of an Excel.Application.
我想打开 Excel 并且仍然能够使用 Excel.Application 的方法。 Is there some way to cast the type or something similar?
有什么方法可以转换类型或类似的东西吗?
use Object
type for myworkbook
variable, too:对
myworkbook
变量也使用Object
类型:
Dim my_path As String
my_path = "some valid path to wanted workbook"
On Error GoTo SafeExit
Dim myexl As Object
Set myexl = CreateObject("Excel.Application")
Dim myworkbook As Object
Set myworkbook = myexl.Workbooks.Open(my_path)
myexl.Visible = True
...
SafeExit:
MsgBox Err.Number & " - " & Err.Description
If Not myexl Is Nothing Then myexl.Quit ' <-- this will close the excel instance you opened (if any)
Set myexl = Nothing
To open an excel file from word, you do need to define myexl as Object.要从 word 打开 excel 文件,您需要将 myexl 定义为 Object。 You also define myworkbook as object.
您还将 myworkbook 定义为 object。
This solution was taken from " https://answers.microsoft.com/en-us/msoffice/forum/all/how-do-i-open-a-specific-excel-file-through-vba-in/19201a70-6afe-4799-96bf-521cc6020718 ".此解决方案取自“ https://answers.microsoft.com/en-us/msoffice/forum/all/how-do-i-open-a-specific-excel-file-through-vba-in/19201a70- 6afe-4799-96bf-521cc6020718 ”。 I tested it just now and it worked, let me know if you run into issues.
我刚刚测试了它,它工作正常,如果你遇到问题,请告诉我。
Dim myexl As Object
Dim myworkbook As Object
Dim my_path As String = "C:\Path\WorkbookName.xlsx"
On Error Resume Next
Set myexl = GetObject(, "Excel.Application")
If Err Then
Set myexl = CreateObject("Excel.Application")
End If
On Error GoTo 0
Set myworkbook = myexl.Workbooks.Open(FileName:=my_path)
myexl.Visible = True
lbl_Exit:
Set myexl = Nothing
Set myworkbook = Nothing
Exit Sub
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.