Hi Joel and also to the OP,
I am really impressed with Joel's input and particularly his last idea for
sorting the datevalues. Overall it is a far better solution, particularly
since FileSearch is no longer supported in xl2007. However, the datevalues
needed another little tweek because the array holds the entire filename
including the .xls ext. I have done this and also included a test for
thisworkbook so that it gets left out of the file list if it just happens to
be in the same folder.
Note that the code should now work for most formats of the date as a
filename even if they are mixed formats such as d-mmm-yy, dd-mm-yyyy.
However, the emphasis is on 'should' because I have not tested it to the nth
degree. The date formats in the original post of dd-mmm-yy should never give
any problems.
Here is a fresh copy of the code with the amendments:-
Sub sortfilename()
Const MyPath = "c:\temp"
Const Filetype = "*.xls"
Dim FileNames(1000)
Dim strThisWb As String
strThisWb = ThisWorkbook.Name
FileCount = 0
First = True
Do
If First = True Then
Filename = Dir(MyPath & "\" & Filetype)
First = False
Else
Filename = Dir()
End If
'Leave out this workbook that contains the macro
If Filename <> "" And Filename <> strThisWb Then
FileNames(FileCount) = Filename
FileCount = FileCount + 1
End If
Loop While Filename <> ""
'sort file names
FileCount = FileCount - 1
For i = 0 To (FileCount - 1)
For j = i To FileCount
If DateValue(Left(FileNames(i), InStr(FileNames(i), ".") - 1)) _
DateValue(Left(FileNames(j), InStr(FileNames(j), ".") - 1)) Then
temp = FileNames(i)
FileNames(i) = FileNames(j)
FileNames(j) = temp
End If
Next j
Next i
'open files
For i = 0 To (FileCount - 1)
'MsgBox only for testing. Delete it and
'remove comment from the following 3 lines
MsgBox FileNames(i)
'Workbooks.Open MyPath & "\" & FileNames(i)
'Enter Your code here
'Workbooks(FileNames(i)).Close
Next i
End Sub
Thanks again Joel for you input here.
Regards,
OssieMac