Can anyone offer an efficient way to get the next number in the sequence of a
file name?

Example. I have a folder containing files: file001.pdf, file002.pdf,
file003.pdf, file005.pdf.

I want to get the next number ie file006.pdf. Note that I have intentionally
left out file004.pdf as files may be removed and not sequential.

Thanks in advanced

Re: Incrementing Filename Number by ekkehard

ekkehard
Thu Mar 01 10:33:24 CST 2007

Paul wrote:

> Can anyone offer an efficient way to get the next number in the sequence of a
> file name?
>
> Example. I have a folder containing files: file001.pdf, file002.pdf,
> file003.pdf, file005.pdf.
>
> I want to get the next number ie file006.pdf. Note that I have intentionally
> left out file004.pdf as files may be removed and not sequential.
>
> Thanks in advanced
If your sample is representative then using a RegExp pattern "(\d+)\.pdf$"
should give you the numbers (with leading zeros). Keeping track of the
largest/widest number seen will allow you to increment and format the
next number.

The demo code uses an array of 'filenames'; the real world script
would get the files via oFS.GetFolder( <FolderName> ).Files and
either collect the names or loop over this collection:

Dim aTests : aTests = Array( _
"file001.pdf", "file002.pdf", "file003.pdf", "file005.pdf" _
)

' aTests = Array( "file000.pdf" )
' aTests = Array( "file999.pdf" )

Dim nFNum : nFNum = -1
Dim nMxLen : nMxLen = 1
Dim reFNum : Set reFNum = New RegExp
reFNum.Pattern = "(\d+)\.pdf$" ' sequence of digits before extension .pdf
reFNum.Global = True
reFNum.IgnoreCase = True

Dim sTest, sMsg, oMTS, sNum, lNum
For Each sTest In aTests
sMsg = ": no match"
Set oMTS = reFNum.Execute( sTest )
If 1 = oMTS.Count Then
If 1 = oMTS( 0 ).SubMatches.Count Then
sNum = oMTS( 0 ).SubMatches( 0 )
If nMxLen < Len( sNum ) Then nMxLen = Len( sNum )
lNum = CLng( sNum )
If nFNum < lNum Then nFNum = lNum
sMsg = ": " + oMTS( 0 ).Value + " => " + CStr( lNum )
End If
End If
WScript.Echo sTest + sMsg
Next
If -1 = nFNum Then
WScript.Echo "No file numbers found"
Else
nFNum = nFNum + 1
sNum = CStr( nFNum )
If nMxLen < Len( sNum ) Then nMxLen = Len( sNum )
sNum = Right( String( nMxLen, "0" ) + sNum, nMxLen )
WScript.Echo "I *think*", sNum, "would be the next number!"
End If