11

我想使用通配符打开存储在与我的宏工作簿相同的文件夹中的工作簿。文件夹中有一个名为302113-401yr-r01.xlsm. 这是我的代码:

Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*.xlsm"

但是,它告诉我没有这样的文件。有什么建议吗?

4

4 回答 4

21

我们无法使用通配符打开文件——如果可以的话,想象一下混乱吧!

您需要使用它Dir(ActiveWorkbook.Path & "\302113*.xlsm")来遍历返回的文件。如果只有一个,则只需使用此功能一次:

Dim sFound As String

sFound = Dir(ActiveWorkbook.Path & "\302113*.xlsm")    'the first one found
If sFound <> "" Then
    Workbooks.Open filename:= ActiveWorkbook.Path & "\" & sFound
End If

目录功能:网络技术

于 2013-10-22T20:28:34.087 回答
3

根据我的经验,如果您将通配符/asterix 作为字符串中的最后一个符号并且只有一个文件,则此方法有效。尝试做:

Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*"

例如我正在使用:

Workbooks.Open Filename:="X:\business\2014\Easy*"

它有效。

于 2014-05-22T09:26:01.560 回答
2

您可以使用通配符打开文件,但出于某种原因只能使用 UNC 路径。

例如 :

Set xlFile = xlObj.WorkBooks.Open("\\yourServerHere\dataAutomation\*.xlsx")
于 2016-04-08T04:29:01.133 回答
2

我对 Excel 的经验还不是很丰富,但以下内容对我来说非常适合在文件名中使用通配符来打开文件。此示例要求所有文件位于同一目录/文件夹中。是的,这很简单。

Sub using_wildcards_to_open_files_in_excel_vba()

    Dim mypath As String
    Dim sFilename As String

    'Suppose you have three files in a folder
    ' Named blank.xlsx,, ex1_939_account.xlsx,  and ex1_opt 5.xlsx

    'Manually open the blank.xlsx file

    'The following code lines will open the second two files before closing the previously opened file.

    ActiveWorkbook.Activate
    mypath = ActiveWorkbook.Path
    'opening xlsx file with name containing "939" and closing current file
    mypath = mypath & "\*939*.xlsx"
    'MsgBox mypath  'Checking
    sFilename = Dir(mypath)
    'MsgBox sFilename  'Checking

    ActiveWorkbook.Close savechanges:=False
    Workbooks.Open Filename:=sFilename

    ActiveWorkbook.Activate
    mypath = ActiveWorkbook.Path
    'opening xlsx file with name ending in "opt 5" and closing current file
    mypath = mypath & "\*opt 5.xlsx"
    'MsgBox mypath  'Checking
    sFilename = Dir(mypath)
    'MsgBox sFilename  'Checking

    ActiveWorkbook.Close savechanges:=False
    Workbooks.Open Filename:=sFilename

End Sub
于 2017-01-30T19:50:57.463 回答