【问题标题】:Set a right path to the excel file knowing only the first part of its name只知道其名称的第一部分,为 excel 文件设置正确的路径
【发布时间】:2017-04-10 13:30:31
【问题描述】:

每日生成的带有数据的新 Excel 文件将具有以下名称:“RawData_今天日期-时间.xlsx”,例如:“Report_2017-04-10- 10-17-42.xlsx”。我正在尝试为文件设置正确的路径,只知道其名称的第一部分并忽略 time-部分?

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

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

结果 -> 找到正确的文件。 第二部分代码:

'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”:抱歉,我们找不到 False.xlsx。是否有可能被移动、重命名或删除?

我不明白为什么它会寻找 False.xlsx?我做错了什么?

任何帮助将不胜感激。

【问题讨论】:

  • 使用通配符 * ,如 RawDataPath = FolderPath & "Report" & Format(Date, "yy-mm-dd") & "*.xlsx"
  • 不起作用,“找不到文件”
  • @ShaiRado 的评论应该有效,但您的问题存在脱节 - 您说文件名将包括 2017-04-10 但您的代码有 format(Date, "yy-mm-dd") 所以使用 Shai 的示例,但使用 @987654327 @
  • 是的,我之前已经修复了这个错误。不工作:(
  • FileExist 过程包含什么?

标签: excel vba


【解决方案1】:

好的,终于找到解决办法了,感谢the 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$ 函数只返回文件名,而不是文件的完整路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多