使用通配符打开Excel工作簿

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

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

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

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

您需要使用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 

Dirfunction :网上技术

根据我的经验,如果将通配符/ asterix作为string中的最后一个符号,并且只有一个文件,那么这将起作用。 尝试做:

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

例如,我正在使用:

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

它的工作。

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

例如 :

 Set xlFile = xlObj.WorkBooks.Open("\\yourServerHere\dataAutomation\*.xlsx") 

我还没有经验丰富的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