Sorting via VBA

amitaj

New Member
Joined
Nov 18, 2020
Messages
1
Office Version
  1. 2016
Platform
  1. Windows
Currently when sorting:

Code
fixed​
114​
24​
234​
3​
345​
350​

What I want:
Code
fixed
1​
3​
24​
114​
234​
345​
350​

Code is the header of the column which begins in Cell A12. I have the "fixed" cell which much remain at the top but the numerical values below should be in ascending order. I want this to run when I save the file.
 

Some videos you may like

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple

JB2020

Board Regular
Joined
Jul 29, 2020
Messages
75
Office Version
  1. 365
  2. 2016
  3. 2010
Platform
  1. Windows
It looks like it's sorting that way because the numbers are stored as text, so you would need to convert them prior to sorting.
 

ekrause

New Member
Joined
Aug 7, 2019
Messages
49
The code to sort will be. I bolded what you will need to change.

VBA Code:
ActiveWorkbook.Worksheets("[B]Sheet6[/B]").Sort.SortFields.Add2 Key:=Range("[B]B5:B10[/B]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal


    With ActiveWorkbook.Worksheets("[B]Sheet6[/B]").Sort
        .SetRange Range("[B]B4:B10[/B]")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
 

JoeMo

MrExcel MVP
Joined
May 26, 2009
Messages
17,361
Office Version
  1. 365
  2. 2010
Platform
  1. Windows
When I copy your example, the numbers appear to be text (containing ChrW8203). In that case try:
VBA Code:
Sub sortIt()
Dim c As Range
With Range("A13:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    For Each c In .Cells
        If Val(c.Value) <> 0 Then c.Value = Val(c.Value)
    Next c
    .Sort key1:=[A14], order1:=xlAscending, Header:=xlYes
End With
End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,118,862
Messages
5,574,715
Members
412,613
Latest member
EFRATA
Top