【问题标题】:Using the Dir function in a Do While Loop (VBA)在 Do While 循环 (VBA) 中使用 Dir 函数
【发布时间】:2020-08-12 21:12:51
【问题描述】:

帮助在 Do While 循环中使用 VBA 中的 Dir 函数

基本上,我试图在一个目录中找到一个文件的最新版本,以便在宏的其他地方使用。这些文件的路径是“A:\HOLD\ReportName-”和“mmddyy”格式的报告日期,后跟我们的 ERP 生成的一系列随机字符。例如“A:\HOLD\ReportName-081220-asdknrtr884”

我希望程序从今天开始查找文件,如果该文件不存在,则每天继续查找,直到找到文件(最多 30 天)。所以081220、081120、081020等

问题在于,Do While 循环只会回顾一天,然后进入无限循环并达到 30 天的最大值,即使文件存在于该时间范围内也是如此。

从我收集的信息来看,它与 Dir() 函数有关,以及它如何保持文件路径值。我只是没有看到针对我的特殊情况的好答案,主要是对何时 Dir "" 或 Len > 0 的答案。

感谢您的帮助!

Dim wb1 As Workbook
    
Dim FilePath As String
Dim FileName As String
Dim FullFile As String
Dim FileDate As String
Dim strFileExists As String
Dim count As Integer
    
FilePath = "A:\HOLD\"
FileDate = Format(Date, "mmddyy")
FileName = "ReportName-" & FileDate & "*"
FullFile = FilePath & FileName
    
strFileExists = Dir(FullFile)
    
Do While strFileExists = ""
    FileDate = Format(Date - 1, "mmddyy")
    FileName = "ReportName-" & FileDate & "*"
    FullFile = FilePath & FileName
    strFileExists = Dir(FullFile)
    count = count + 1

    If count > 30 Then
        MsgBox "There has not been a report in over 30 days, please run a new report"
        Exit Do     
        Exit Sub
    End If
Loop

Set wb1 = Workbooks.Open(FullFile)

'''

【问题讨论】:

  • FileDate = Format(Date - 1, "mmddyy") - 您希望在循环的每次迭代中如何改变?这只会是Date - 1,或昨天的日期。您需要建立一个等于今天日期的变量,然后在每次迭代中从中减去 1 天。
  • 是的,就是这样,现在我觉得自己像个白痴。将 Dir() 函数追到一个兔子洞里,完全忽略了日期。

标签: excel vba


【解决方案1】:

试试这个:

Sub Test()

    Dim wb1 As Workbook
        
    Dim FilePath As String
    Dim FileName As String
    Dim FullFile As String
    Dim FileDate As String
    Dim strFileExists As String
    Dim count As Integer
    Dim i As Long
    
    FilePath = "A:\HOLD\"
    FileDate = Format(Date, "mmddyy")
    FileName = "ReportName-" & FileDate & "*"
    FullFile = FilePath & FileName
        
    strFileExists = Dir(FullFile)
    count = 1
    
    Do While strFileExists = ""
        FileDate = Format(Date - count, "mmddyy")
        FileName = "ReportName-" & FileDate & "*"
        FullFile = FilePath & FileName
        strFileExists = Dir(FullFile)
        count = count + 1
    
        If count > 30 Then
            MsgBox "There has not been a report in over 30 days, please run a new report"
            Exit Do
            Exit Sub
        End If
    Loop
    
    Set wb1 = Workbooks.Open(FullFile)

End Sub

【讨论】:

  • 好吧,我是个白痴,花了几个小时在错误的地方寻找。谢谢!
  • 常见错误!祝你好运
猜你喜欢
  • 2023-03-20
  • 2021-03-08
  • 2021-07-18
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 2018-01-16
相关资源
最近更新 更多