I'm using the sort procedure in Excel VBA and want to have a variable set that changes the order to ascending or descending, depending on a condition. I tried this but am getting a "type mismatch" error.
If SBF = 0 Then
S = "xlAscending"
Else: S = "xlDescending"
End If
ActiveWorkbook.Worksheets(SN(x)).sort.SortFields.Add Key:=Range( _
"B3:B" & last_cell), SortOn:=xlSortOnValues, Order:=S, DataOption:= _
xlSortNormal
xlAscending
andxlDescending
are Excel Constants. To see what values they have simply print it in Immediate window. See the snapshot below.So you can actually write your code as
Similarly the values of
xlSortOnValues
andxlSortNormal
is0
. If you want you can also write the above code asEDIT
I am assuming that
S
has been declared as an Integer or a Long and not as a String.This works: