I have list CSV files in a specific order in Col A on sheet "JNL Uploads"
The CSV files are exported to C:\Sales JNLS" and I would like these to be sorted in the same order as in Col A on sheet "JNL Uploads"
I have tried to write code to do this, but get a run time eerror type mismatch and the code below is highlighted
It would be appreciated if someone could kindly check my code and amend it
The CSV files are exported to C:\Sales JNLS" and I would like these to be sorted in the same order as in Col A on sheet "JNL Uploads"
I have tried to write code to do this, but get a run time eerror type mismatch and the code below is highlighted
Code:
fileNames = WorksheetFunction.Transpose(ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row).Value)
It would be appreciated if someone could kindly check my code and amend it
Code:
Sub SortCVSFiles()
Dim wb As Workbook
Dim ws As Worksheet
Dim filePath As String
Dim fileNames() As String
Dim i As Long, j As Long, k As Long
Dim temp As String
' Set workbook and worksheet variables
Set wb = ActiveWorkbook
Set ws = wb.Sheets("JNL Uploads")
' Get file names from column A and convert to strings
fileNames = WorksheetFunction.Transpose(ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row).Value)
For i = LBound(fileNames) To UBound(fileNames)
fileNames(i) = CStr(fileNames(i))
Next i
' Sort the file names array
For i = LBound(fileNames) To UBound(fileNames) - 1
For j = i + 1 To UBound(fileNames)
If StrComp(fileNames(i), fileNames(j), vbTextCompare) > 0 Then
temp = fileNames(i)
fileNames(i) = fileNames(j)
fileNames(j) = temp
End If
Next j
Next i
' Loop through the sorted file names and move the files
filePath = "C:\Sales JNLS\"
For k = LBound(fileNames) To UBound(fileNames)
If Len(Dir(filePath & fileNames(k))) > 0 Then
Name filePath & fileNames(k) As filePath & "temp"
Name filePath & fileNames(k) As filePath & fileNames(k)
Name filePath & "temp" As filePath & fileNames(k)
End If
Next k
' Notify user that sorting is complete
MsgBox "File names sorted in C:\Sales JNLS folder."
End Sub