只知道其名称的第一部分,设置一个正确的path到Excel文件

每天生成带有数据的新Excel文件将具有以下名称:“RawData_ todaydate时间 .xlsx”,例如:“Report_2017-04-10-10-17-42.xlsx”。 我试图设置一个正确的文件path,只知道其名称的第一部分,而忽略时间部分?

正如@ShaiRado和@RobinMackenzie所build议的那样,下面的代码应该可以正常工作:

Dim RawDataPath As String Dim FolderPath As String FolderPath = ThisWorkbook.Path & "\" RawDataPath = FolderPath & "Report" & format(Date, "yyyy-mm-dd") & "*.xlsx" 

但是,我仍然收到错误消息,我认为这个问题不在上面。

我找了一个文件使用

 RawDataPath = Dir$(FolderPath & "Report" & format(Date, "yyyy-mm-dd") & "*.xlsx") If (Len(RawDataPath) > 0) Then MsgBox "found " & RawDataPath End If 

结果 – >find正确的文件。 代码的第二部分:

 'check if the file exists If FileExists(RawDataPath) = False Then RawDataPath = BrowseForFile("File not found. Please select the file.") 'check if the workbook is open If Not IsWbOpen(RawDataPath) Then Workbooks.Open RawDataPath 

检查文件是否存在失败。 运行时错误“1004”:对不起,我们无法findFalse.xlsx。 它可能被移动,重命名或删除?

我不知道为什么它会寻找一个False.xlsx? 我究竟做错了什么?

任何帮助,将不胜感激。

好的,终于find了解决办法,感谢post :

 Dim RawDataPath As String Dim FolderPath As String FolderPath = ThisWorkbook.Path & "\" RawDataPath = Dir$(FolderPath & "Report" & format(Date, "yyyy-mm-dd") & "*.xlsx") If (RawDataPath <> "") Then Workbooks.Open FolderPath & RawDataPath Else MsgBox "not found" End If 

注意:Dir $函数仅返回文件的名称,而不是它的整个path。