Home » excel » excel – Store folder names into array and sort alphabetically VBA

excel – Store folder names into array and sort alphabetically VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have the following code which is meant to pull each file name in a specific path and place it into an array. For some reason, although the files in the File Explorer are sorted alphabetically, the code is pulling them out of order. My approach is to first store the file names into the array first, then sort the array afterwards. Is there a better way to approach this?

Additionally, for some reason the line with Debug.Print arr1(i) only prints blanks to the immediate window. Please advise.

Dim arr1(1000) As String, item As Variant
Dim x As Long, y As Long, k As Integer
Dim TempTxt1 As String
Dim TempTxt2 As String
Dim FolderPath As String, path As String, count As Integer
Dim size As Integer, i As Integer

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFSO.GetFolder("X:\test\testfolder")

For Each oFile In oFolder.Files

    arr1(i) = Left(oFile.Name, Application.WorksheetFunction.Find(".", oFile.Name) - 1)

    i = i + 1

    Debug.Print arr1(i)

Next oFile


'Alphabetize Sheet Names in Array List
  For x = LBound(arr1) To UBound(arr1)
    For y = x To UBound(arr1)
      If UCase(arr1(y)) < UCase(arr1(x)) Then
        TempTxt1 = arr1(x)
        TempTxt2 = arr1(y)
        arr1(x) = TempTxt2
        arr1(y) = TempTxt1
      End If
     Next y
  Next x

enter code here

How to&Answers:

So as per my comment; I think you might benefit from using ArrayList and its ability to Sort. Try:

Sub Test()

Dim oFSO As Object, oFolder As Object, arr As Object

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("X:\test\testfolder")
Set arr = CreateObject("System.Collections.ArrayList")

For Each oFile In oFolder.Files
    arr.Add oFSO.GetBaseName(oFile)
Next oFile

arr.Sort

End Sub

Since you pull in names one-by-one we might as well do so in the ArrayList. The .Sort method will then sort the list in ascending order.