VBA打开excel工作簿基于文件名的第一部分?

时间:2017-03-03 12:05:58

标签: excel vba

我正在尝试使用vba打开excel工作簿:

'Open Planner
On Error Resume Next
Set WB = Workbooks("(FILE NAME).xlsx")
On Error GoTo 0
If WB Is Nothing Then 'open workbook if not open
    Set WB = Workbooks.Open("G:\BUYING\Food Specials\6. Depot Memos\" & ThisWorkbook.Worksheets(1).Range("T8").value & "\(File Name).xlsx", Password:="samples", WriteResPassword:="samples", UpdateLinks:=False)
End If

我遇到的问题是我的文件更改名称不时如此:

Depot Memo 12 - 13
Depot Memo 13 - 14
Depot Memo 15 - 16

如何根据文件名“Depot Memo”的第一部分打开文件? 我是VBA的新手,所以我真的很感激任何帮助。

提前致谢

1 个答案:

答案 0 :(得分:1)

根据here的答案(Shout-out to @Alex K。)尝试此示例:

只需替换您的代码部分:

'Open Planner
'This is your routine here
On Error Resume Next
Set WB = Workbooks("(FILE NAME).xlsx")
On Error GoTo 0
If WB Is Nothing Then 'open workbook if not open
    Set WB = FindDepotMemo
End If
'and there you need another check if WB is nothing

并将此功能添加到您的项目中:

Function FindDepotMemo() As Workbook
    Dim Path As String
    Dim FindFirstFile As String

    Path = "G:\BUYING\Food Specials\6. Depot Memos\" & ThisWorkbook.Worksheets(1).Range("T8").Value & "\"

    FindFirstFile = Dir$(Path & "Depot Memo*.xlsm")

    If (FindFirstFile <> vbNullString) Then
        Set FindDepotMemo = Workbooks.Open(Filename:=Path & FindFirstFile, Password:="samples", WriteResPassword:="samples", UpdateLinks:=False)
    End If
End Function