Consulting

Results 1 to 4 of 4

Thread: VBA code to sort a sheet

  1. #1

    VBA code to sort a sheet

    Hi

    I have a user form that i use to add a companys details to a sheet.
    when i enter the data i would like to sort the companys so they are in order.
    this is the code i have so far but this sorts a static range of cells, but i need it to sort the new entry aswell.

    Sheets("Payee").Select
    Range("B2").Select
    ActiveWorkbook.Worksheets("Payee").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Payee").Sort.SortFields.Add Key:=Range("B2"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Payee").Sort
    .SetRange Range("B2:C20")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
    End With

    thanks ash

  2. #2
    VBAX Mentor
    Joined
    Jul 2012
    Posts
    398
    Location
    Sub a()
    Worksheets("Payee").Select
    LR = Cells(Rows.Count, "B").End(xlUp).Row
    Range("B2:C" & LR).Sort key1:=Range("B2"), order1:=xlAscending, Header:=xlNo, DataOption1:=xlSortTextAsNumbers
    End Sub

  3. #3
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
    Usually, the first column requires a data input. As such, I usually find the last row that way. e.g.
    Range("B2:C" & Range("B" & Rows.Count).End(xlUp).Row)
    Obviously, this would be used for the SetRange.

  4. #4
    That worked great thanks so much

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •