簡體   English   中英

在 Word 中從 VBA 打開 Excel

[英]Open Excel from VBA 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)

但是,第 (2) 行在上述代碼中生成“類型不匹配”。 如果我嘗試切換 (1) 以使其改為

Dim myexl As Object

然后(2)有效,但現在我得到第(3)行的“對象不支持此屬性或方法”。 這就像一個陷阱 22。

我該如何解決這個問題? 我想打開 Excel 並且仍然能夠使用 Excel.Application 的方法。 有什么方法可以轉換類型或類似的東西嗎?

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

要從 word 打開 excel 文件,您需要將 myexl 定義為 Object。 您還將 myworkbook 定義為 object。

此解決方案取自“ 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 ”。 我剛剛測試了它,它工作正常,如果你遇到問題,請告訴我。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM