识别仅具有部分已知名称的文件

时间:2014-10-06 20:20:59

标签: vba excel-vba excel

我有一个保存文件的宏,命名模式是Myfile_ddmmyyyy_hhmmss.rep(ddmmyyyy_hhmmss代表当前日期和时间:))。

我努力实现的是编写一个宏来识别名称中包含最新日期和时间的文件。我所拥有的是:

Sub App_FileSearch_Example()

Const SOME_PATH As String = "t:\"

Dim file As String
Do
file = Dir$(SOME_PATH & "MyFile_ddmmyyyy_hhmmss" & ".rep")

    If (Len(file) > 0) Then
    MsgBox "found " & file
    End If
Loop Until file = Dir$()
End Sub

问题在于它无限地找到相同的文件...
提前谢谢,
阿图尔。

1 个答案:

答案 0 :(得分:0)

尝试对您的代码进行此修改。它编译但我没有用.rep文件的文件夹测试它。

Sub App_FileSearch_Example()
    Dim fn As String, tmp As String, theNewest As String, dtFn As Date
    Const SOME_PATH As String = "t:\"

    theNewest = "nothing found"
    fn = Dir$(SOME_PATH & "MyFile_*.rep")
    Do While CBool(Len(fn))
        tmp = Left(fn, InStr(1, fn, Chr(46)) - 1)       'truncate at the period
        tmp = Mid(tmp, InStr(1, tmp, Chr(95)) + 1, 99)  'split off at the first _
        tmp = Replace(tmp, Chr(95), Chr(32))            'replace the _ in the datetime
        If DateValue(tmp) > dtFn Then
            dtFn = DateValue(tmp)
            theNewest = fn
        End If
        fn = Dir$()
    Loop
    MsgBox "found " & theNewest
End Sub