Sorting via VBA

amitaj

New Member
Joined
Nov 18, 2020
Messages
2
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.
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
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.
 
Upvote 0
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
 
Upvote 0
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
 
Upvote 0

Forum statistics

Threads
1,213,513
Messages
6,114,064
Members
448,545
Latest member
kj9

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top