I have the following code used to merger PDF files picked by the user. However the issue is that the files being mergerd is not in the order of its file name.

Is there any method we can use to sort the file name prior to the merging part?



Sub Main()

Const DestFile As String = "MergedFile.pdf" ' <-- change to suit

Dim MyPath As String, MyFiles As String
Dim a() As String, i As Long, f As String

' Choose the folder or just replace that part by: MyPath = Range("E3")
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False

If .Show = False Then Exit Sub

MyPath = .SelectedItems(1)
DoEvents
End With

' Populate the array a() by PDF file names
If Right(MyPath, 1) <> "" Then MyPath = MyPath & ""
ReDim a(1 To 2 ^ 14)
f = Dir(MyPath & "*.pdf")
While Len(f)
If StrComp(f, DestFile, vbTextCompare) Then
i = i + 1
a(i) = f
End If
f = Dir()
Wend


' Merge PDFs
If i Then
ReDim Preserve a(1 To i)
MyFiles = Join(a, ",")
Application.StatusBar = "Merging, please wait ..."
Call MergePDFs(MyPath, MyFiles, DestFile)
Application.StatusBar = False
Else
MsgBox "No PDF files found in" & vbLf & MyPath, vbExclamation, "Canceled"
End If

End Sub