I use Office for Mac and I want to open Excel (and then a document within it) using a macro in Word.
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. If I try to switch (1) so that instead it reads
Dim myexl As Object
then (2) works but now I get "Object doesn't support this property or method" for line (3). This is like a catch 22.
How can I solve this? I want to open Excel and still be able to use the methods of an Excel.Application. Is there some way to cast the type or something similar?
use Object
type for myworkbook
variable, too:
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. You also define myworkbook as 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 ". 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.