使用数组循环遍历文件夹以使用 VBA 查找最新版本(计数)?

Loop through folder using array to find lastest version (count) with VBA?

我附上了代码,但是,这只会找到文件夹中存在的文件。
我想要的是文件的增量计数器。问题是有时版本会以 0 或 1 以外的其他内容开头,例如3.
Amesto non AN suppliers TEST W20-3 AN 那么我希望下一个字符串是 4。

我目前正在使用它,但只有当 1 是第一个时它才有效,等等。 我真的卡住了。

' Version check
    Do While Len(Dir(strPath2 & "Amesto non AN suppliers TEST W" & week & "-" & version & "*.cif")) <> 0
        version = version + 1
        strPath = getDirectoryPath & "Amesto non AN suppliers TEST W" & week & "-" & version & " " & UserName & ".cif"
    Loop


Sub loadversion()
Dim MyFile As String
Dim Counter As Long

'Create a dynamic array variable, and then declare its initial size
Dim DirectoryListArray() As String
ReDim DirectoryListArray(1000)

'Loop through all the files in the directory by using Dir$ function
MyFile = Dir$("C:\Users\niclas.madsen\Desktop\AP\WAVE3\CIF\*.*")
Do While MyFile <> ""
    DirectoryListArray(Counter) = MyFile
    MyFile = Dir$
    Counter = Counter + 1
Loop

' do something here?!
If MyFile = vbNullString Then

Else

End If 

'Reset the size of the array without losing its values by using Redim Preserve
ReDim Preserve DirectoryListArray(Counter - 1)

For Counter = 0 To UBound(DirectoryListArray)
    'Debug.Print writes the results to the Immediate window (press Ctrl + G to view it)'
    Debug.Print DirectoryListArray(Counter)
Next Counter 
End Sub

要获取目录中文件名的最高版本,请插入以下函数:

Function CheckHighestVersion(path As String, cutLettersAtWordBeginning As Integer) As Integer
    Dim file As Variant
    Dim toBeCut As String
    Dim verLength As Integer
    Dim highestVersion As Integer
    highestVersion = 0
    file = Dir(path)

    While (file <> "")
        toBeCut = file
        toBeCut = Mid(toBeCut, cutLettersAtWordBeginning + 1)
        verLength = FindVerLength(toBeCut)
        If verLength = -1 Then
            CheckHighestVersion = 0
            Exit Function
        End If
        toBeCut = Left(toBeCut, verLength)
        If Val(toBeCut) > highestVersion Then
            highestVersion = Val(toBeCut)
        End If
        file = Dir
    Wend
    CheckHighestVersion = highestVersion
End Function

Function FindVerLength(fileName As String) As Integer
    Dim i As Integer
    For i = 1 To Len(fileName)
        If Not IsNumeric(Mid(fileName, i, 1)) Then
            If i = 1 Then
                MsgBox "Couldn't obtain the highest version of the files: " & _
                "The first letter of the version is not numeric. The letter is " & Mid(fileName, i, 1) & _
                ". Please use correct amount of letters to be cut at the beginning of the file name."
                FindVerLength = -1
                Exit Function
            End If
            FindVerLength = i - 1
            Exit Function
        End If
    Next i
    FindVerLength = i
End Function

在您的 Sub 中调用 CheckHighestVersion。路径只是目录(例如 C:\Test\ ),第二个参数是单词开头不需要的字母数。如果我计算正确,在您的情况下,该值应为 30+(周长,第 25 周为 2,第 7 周为 1)。函数 returns 该文件夹中包含的最高版本。