Find the next file number


Q: I have an application that saves information in files. The file names consist of 4characters + a running number. How can I find the next available number ?

A. This procedure should solve your problem

Sub FindNextFileNumber()

  'This procedure requires a reference to the Microsoft Scripting Runtime library

  Dim fso As FileSystemObject
  Dim fld As Folder, fil As File
  Dim intHighestValue As Integer
  Dim strFileName As String, strLastChars As String

  intHighestValue = 0                                'Start on zero

  Set fso = New FileSystemObject
  Set fld = fso.GetFolder("C:/test")                 'Find the folder

  For Each fil In fld.Files                          'For each file in this folder
    strFileName = Left$(fil.Name, Len(fil.Name) - 4) 'Remove the 4 last characters
    strLastChars = Mid(strFileName, 5)               'Remove the 4 first characters

    'Is the remainder higher than the previous highest value ?
    If intHighestValue < CInt(strLastChars) Then   
      intHighestValue = CInt(strLastChars)           'Then set a new highest value
    End If
  Next
  MsgBox "Next number is " & intHighestValue + 1     'Report result
End Sub