Code:
CSV_Files()
Dim M As Integer
Dim FirstWSToSort As Integer
Dim LastWSToSort As Integer
Dim SortDescending As Boolean
'Just setting up for the open file portion
Set fso = CreateObject("Scripting.FileSystemObject")
'Change the folder to the location where the CSV files are stored
csvfoldername = "C:\files"
Set CSVfolder = fso.GetFolder(csvfoldername)
For Each file In CSVfolder.Files
If Right(file.Name, 4) = ".csv" Then
Sheets.Add
'Names the sheet after the file - restricts length to maximum 31 characters
'allowed when naming an excel sheet
ActiveSheet.Name = Left(file.Name, 31)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & file, Destination:=Range("A1"))
.Name = Right(file.Name, (Len(file.Name) - Len(csvfoldername)))
.PreserveFormatting = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePlatform = xlWindows
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileCommaDelimiter = True
.Refresh BackgroundQuery:=False
End With
End If
Next
'get rid of the default sheets we did not use
Application.DisplayAlerts = False
For Each Worksheet In Worksheets
If Left(Worksheet.Name, 5) = "Sheet" Then
Sheets(Worksheet.Name).Delete
End If
Next
SortDescending = False
If ActiveWindow.SelectedSheets.Count = 1 Then
FirstWSToSort = 1
LastWSToSort = Worksheets.Count
Else
With ActiveWindow.SelectedSheets
For N = 2 To .Count
If .Item(N - 1).Index <> .Item(N).Index - 1 Then
MsgBox "You cannot sort non-adjacent sheets"
Exit Sub
End If
Next N
FirstWSToSort = .Item(1).Index
LastWSToSort = .Item(.Count).Index
End With
End If
For M = FirstWSToSort To LastWSToSort
For N = M To LastWSToSort
If SortDescending = True Then
If Int(Mid(Worksheets(N).Name, 6)) > _
Int(Mid(Worksheet(M).Name, 6)) Then
Worksheets(N).Move Before:=Worksheets(M)
End If
Else
If Int(Mid(Worksheets(N).Name, 6) < _
Int(Mid(Worksheet(M).Name, 6) Then
Worksheet(N).Move Before:=Worksheet(M)
End If
End If
Next N
Next M
Application.DisplayAlerts = True
'tidy up
Set fso = Nothing
End Sub
As I am stepping throught this, the error is occuring here:
Code:
If Int(Mid(Worksheets(N).Name, 6) < Int(Mid(Worksheet(M).Name, 6)
any ideas why?