Goal
The goal of this task is to:
- Find the most recent Excel file in the directory,
- Sort that file using a custom list (defined in code below),
- Save the sorted file under the same name, and
- Have Windows Scheduler run the VB script every 10 minutes.
My attempt
I have compiled this code, yet I get an error message when I try to run it:
'Find the most recent file in directory
Option Explicit
Dim fso, path, file, recentDate, recentFile, objExcel, objWorkbook, objRange, objWorksheet, SortCol
Set fso = CreateObject("Scripting.FileSystemObject")
Set recentFile = Nothing
For Each file in fso.GetFolder("C:\Users\joe\Documents\test\").Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf file.DateLastModified > recentFile.DateLastModified Then
If Left(recentFile.name, 2) = "~$" Then
Set recentFile = file
End If
End If
Next
'Open the most recent file
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(recentFile.Path)
Set objWorksheet = objWorkbook.Worksheets("Sheet1")
'Sort by custom array
objWorksheet.Sort.SortFields.Clear
objWorksheet.Sort.SortFields.Add key:=Range("A1:A20") _
, SortOn:=xlSortOnValues, Order:=xlDescending, CustomOrder:= _
"alpha,bravo,charlie,delta,echo,foxtrot,golf,hotel,india,juliet", DataOption _
:=xlSortNormal
With objWorksheet.Sort
.SetRange Range("A1:B20")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Save Excel workbook with same name
objWorkbook.save
objExcel.quit
Error message
Line: 23
Char: 38
Error: Expected statement
Code: 800A0400
Source: Microsoft VBScript compilationerror