I registered an excel vba type but I do not understand the lines of code

advertisements

I am new to VBA, therefore i often record anything in excel and use the recorded code. Unfortunately I do not understand the following sort code.

Private Sub SortType()
    ActiveWorkbook.Worksheets("Requirements").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Requirements").Sort.SortFields.Add Key:=Range( _
        "C6:C" & usedRows), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("Requirements").Sort
        .SetRange Range("B6:T" & usedRows)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

What does the first line Sort.SortFields.Clear (and do I really need it?) and for what do I need the With-method?

Thank you for your help! :)


The first line clears any existing sort information (note it does not actually sort anything). The With block simply saves writing the ActiveWorkbook.Worksheets("Requirements").Sort part on each line inside that block. Without it the code would have to be:

Private Sub SortType()
    ActiveWorkbook.Worksheets("Requirements").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Requirements").Sort.SortFields.Add Key:=Range( _
        "C6:C" & usedRows), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal

    ActiveWorkbook.Worksheets("Requirements").Sort.SetRange Range("B6:T" & usedRows)
    ActiveWorkbook.Worksheets("Requirements").Sort.Header = xlGuess
    ActiveWorkbook.Worksheets("Requirements").Sort.MatchCase = False
    ActiveWorkbook.Worksheets("Requirements").Sort.Orientation = xlTopToBottom
    ActiveWorkbook.Worksheets("Requirements").Sort.SortMethod = xlPinYin
    ActiveWorkbook.Worksheets("Requirements").Sort.Apply
End Sub