使用通配符从文件夹中获取文件名

时间:2020-01-03 01:39:33

标签: excel vba

我是VBA的新手,在搜索该问题时遇到了一些麻烦,因为变量具有多种含义。

我正在尝试打开文件并将其名称分配给变量。尽管我总是将文件下载到同一文件夹(仅该文件夹中的一个文件),但文件的名称从未相同。关于文件的唯一可识别的内容是3个字母“ ABC”。

到目前为止,我设法打开了文件,但没有将非标准化文件名分配给变量。

 Sub openwb()

 Dim wb As Workbook Dim directory As String

 directory = "D:\Users\AAA\Desktop\Practice"

 Set FSO = CreateObject("Scripting.FileSystemObject")
 Set folder = FSO.GetFolder(directory)


 For Each file In folder.Files
     If Mid(file.Name, InStrRev(file.Name, ".") + 1) = "xlsm" Then
         Workbooks.Open directory & Application.PathSeparator & file.Name
     End If
 Next file 
 End Sub

 Public Sub RecordFileName()

 Dim sPath As String, sFile As String
 Dim wb As Workbook

 sPath = "D:\Users\AAA\Desktop\Practice"
 sFile = sPath & "*ABC*"
End Sub

1 个答案:

答案 0 :(得分:0)

这是您可以使用的功能。它将返回您要查找的文件名,并且您可以根据需要指定文件模式,也可以忽略该参数,并假定所有文件。

Function GetFullFileName(sFolder As String, Optional sPattern As String = "*") As String
  Dim sFile As String

  ' ensure sFolder ends with a backslash
  If Right$(sFolder, 1) <> "\" Then sFolder = sFolder & "\"

  sFile = Dir(sFolder & sPattern)
  If sFile = "" Then
    MsgBox "NOT FOUND: " & sFolder & sPattern
    End
  End If
  GetFullFileName = sFolder & sFile

End Function

用法:

MsgBox GetFullFileName("C:\Users\Fred\Documents")

MsgBox GetFullFileName("C:\Users\Fred\Documents\", "*ABC*.xlsm")

sFullFile = GetFullFileName("C:\Users\Fred\Documents\", "*ABC*.xlsm")