I've got an Excel VBA script to reformat and sort data I import from a CSV file. The script was developed with Excel 2013, and it used to work fine. I updated Office 2013 to 2019, and the script fails with runteim error 91 "Object variable or With-Block variable not set".
The part of the code which fails is:
Range("A1").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Tabelle1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Tabelle1").AutoFilter.Sort.SortFields.Add Key:= _
Range("A2:A10001"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("Tabelle1").AutoFilter.Sort.SortFields.Add Key:= _
Range("D2:D10001"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("Tabelle1").AutoFilter.Sort.SortFields.Add Key:= _
Range("E2:E10001"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Tabelle1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
The error occurs at line ActiveWorkbook.Worksheets("Tabelle1").AutoFilter.Sort.SortFields.Clear
I tried to find out more by recording a macro. The steps recorded are:
- Click at cell A1
- Activar filters
- Open sort dialogue and add two columns as sort keys, close dialog
- End recording
This is what Excel recorded
Sub Makro1()
'
' Makro1 Makro
'
'
Range("TimeData5[[#Headers],[Start]]").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Tabelle1").ListObjects("TimeData5").Sort.SortFields. _
Clear
ActiveWorkbook.Worksheets("Tabelle1").ListObjects("TimeData5").Sort.SortFields. _
Add2 Key:=Range("TimeData5[Start]"), SortOn:=xlSortOnValues, Order:= _
xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Tabelle1").ListObjects("TimeData5").Sort.SortFields. _
Add2 Key:=Range("TimeData5[Dauer]"), SortOn:=xlSortOnValues, Order:= _
xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Tabelle1").ListObjects("TimeData5").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
The main difference between my code and the recorded one is .ListObjects("TimeData5")
in all the sort operations.
The object name (TimeData5
) seems to be the the file name of the CSV file the data was imported from, amended by a numeric suffix. The problems with this:
- The name of the CSV file changes.
- The suffix is set, and incremented, by Excel in some known mannor.
Why is ListObjects()
needed in Excel 2019, but it was not in Excel 2013?
Is there a workaround to write the VBS so that it is not dependent on the CSV file name?