遍历目录并获取修订版本号最高的文件

时间:2018-07-27 13:54:37

标签: excel vba excel-vba

首先,我会说我在Excel和VBA代码方面没有太多经验,但是我已经遍历了无数资源来寻找这一点。

我试图将所有文件存储在数组中的当前工作目录中,然后遍历该数组以找到每个基本名称末尾编号最高的文件。 示例:file1.xlsx,file2.xlsx,anotherfile1.xlsx,anotherfile2.xlsx 只会返回file2.xlsx和anotherfile2.xlsx。

这是我目前的起点:

Dim directory As String, fileName As String, sheet As Worksheet
Dim fileArray() As String
Dim count As Integer
Set count = 0

Application.ScreenUpdating = False
directory = ActiveWorkbook.Path
fileName = Dir(directory & "*.xlsm")

Do Until fileName = ""
    count = count + 1
    ReDim Preserve fileArray(1 To count)
    fileArray(count) = fileName
    fileName = Dir
Loop

'Find unique entries
For Each element In fileArray
    'do stuff here...
Next element

文件名格式奇怪,所以我不确定该如何处理。文件名如下:GENERICNAME- [我需要比较的字段]-[number] .xlsx

1 个答案:

答案 0 :(得分:1)

下面的 strPath是具有您要查找的名称的最新文件。

Dim fsoFile As New FileSystemObject
Dim fldFile As Folder: Set fldFile = fsoFile.GetFolder(ActiveWorkbook.Path)
Dim objFile As File
Dim dtFile As Date: dtFile = DateSerial(1900, 1, 1)
Dim strPath As String

For Each objFile In fldFile.Files
    If Not objFile.Name Like "*~$*" Then
        If objFile.Name Like "*[file I need to compare]*" _
        And objFile.DateLastModified > dtFile Then
            dtFile = objFile.DateLastModified
            strPath = objFile.Path
        End If
    End If
Next objFile
Set fsoFile = Nothing
Set fldFile = Nothing