0

我需要在给定目录中找到具有最新日期的文件。我不是VB6 的初学者,这就是我需要用于一些旧代码的东西。在下面整天杀死谷歌之后,我到目前为止所拥有的。但它没有找到正确的文件。有人可以帮忙吗?谢谢

Dim sFile1  As String
Dim sFile2 As String
Dim dFile1Date As Date
Dim dFile2Date As Date

sFile1 = Dir("c:\test\*.*", vbNormal)

Do
    sFile2 = Dir
    If sFile1 <> "" Then dFile1Date = FileDateTime("c:\test\" & sFile1)
    If sFile2 <> "" Then dFile2Date = FileDateTime("c:\test\" & sFile2)

    If dFile1Date > dFile2Date Then sFile2 = sFile1

Loop Until sFile2 = ""

FormVersionDate = sFile1
Call MsgBox(FormVersionDate, vbExclamation, App.Title)
4

2 回答 2

3

如果您单步执行您的代码,您会发现sFile1无论您的逻辑结果如何,它都不会被重新分配,因此在最后调用它的值会使您的所有 do 循环无关紧要。此外,它看起来FormVersionDate可能应该是一个日期,但您却为它分配了一个字符串。

我用嵌套循环重写了你的代码,以避免与过多评论无关的逻辑:

Dim sFile1  As String
Dim sFile2 As String
Dim dFile1Date As Date
Dim dFile2Date As Date

'Get first File
sFile1 = Dir("c:\test\*.*", vbNormal)
'Make sure file exists
If sFile1 <> "" Then
    'Since file exists retrieve DateTime for file
    dFile1Date = FileDateTime("c:\test\" & sFile1)
    'begin loop for other files
    Do
        'Retrieve new file
        sFile2 = Dir
        'Make sure file exists
        If sFile2 <> "" Then
            'Retrieve DateTime for file
            dFile2Date = FileDateTime("c:\test\" & sFile2)
            'If old DateTime is older than new DateTime
            If dFile1Date < dFile2Date Then
                'Overwrite first file variables with newer file info
                sFile1 = sFile2
                dFile1Date = dFile2Date
            End If
        End If
        'Loop until new file doesn't exist
    Loop Until sFile2 = ""
End If
'If you actually want the date, you should use dFile1Date instead of sFile1.
FormVersionDate = sFile1
Call MsgBox(FormVersionDate, vbExclamation, App.Title)
于 2012-11-10T00:25:37.903 回答
2

尝试通过变量名进行通信有很多话要说。结果通常比添加大量补偿性评论要清晰得多,尤其是在较短的程序中。

Dim Directory As String
Dim CurrFile As String
Dim CurrDate As Date
Dim NewestDate As Date
Dim NewestFile As String

Directory = "c:\test\"
CurrFile = Dir$(Directory & "*.*", vbNormal)
Do While Len(CurrFile) > 0
    CurrDate = FileDateTime(Directory & CurrFile)
    If CurrDate > NewestDate Then
        NewestDate = CurrDate
        NewestFile = CurrFile
    End If
    CurrFile = Dir$()
Loop
MsgBox CStr(NewestDate) & vbNewLine & NewestFile

请注意,这不会检测并警告其中没有可见文件的目录。不过,您可以只寻找一个空的 ("") NewestFile

于 2012-11-10T19:32:19.397 回答