VBA Excel 无法打开外部工作簿

问题描述 投票:0回答:1

我在这里找到了一个不错但不完整的解决方案: Excel VBA 打开工作簿及其部分名称

并根据我的示例制定了代码

选项显式

Sub NewWorksheet()

Dim sFound As String, fPath As String
Dim WB1 As Workbook

fPath = ThisWorkbook.Path
sFound = Dir(fPath & "Advanced Risk Management Report*.xlsx")
If sFound <> "" Then
Set WB1 = Workbooks.Open(fPath & Found)
End If


End Sub

不幸的是,该代码不起作用。也没有错误。 这里可能缺少什么?

excel vba
1个回答
0
投票

首先选择工具 > 选项并勾选需要变量声明
在以后的所有新模块中,您将在模块顶部看到Option Explicit

enter image description here

现在只需更新您的代码,如下所示:

Option Explicit

Sub NewWorksheet()

    Dim sFound As String, fPath As String
    Dim WB1 As Workbook
    
    fPath = ThisWorkbook.Path & "\" 'Added & "\"
    sFound = Dir(fPath & "Advanced Risk Management Report*.xlsx")
    If sFound <> "" Then
        Set WB1 = Workbooks.Open(fPath & sFound) 'Updated Found to sFound.
    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.