Sort Range by Date Value in Column - vba

The following code below execute fine but the output of the sort function is a mess.
Intention of code is to sort range of values from B2 to last row of L
According to DD/MM/YYYY HH:MM:SS value
Code is used to sort a series of files in a folder, so a simple macro recording won't suffice
Dim Slrow As Long
'Updated last row count to Column B from comment made
Slrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("B2:L" & Slrow).Sort Key1:=Range("B2:L" & Slrow), Order1:=xlAscending, Header:=xlNo
SortWb.Close SaveChanges:=True
Output of Code
File Download link available below ->
Download
Sorting with Custom Sort

The problem is the Key and the range where you apply it, and also the options (looks like your data got headers in row 1). Try something like this:
Range("B1:L" & Slrow).Sort Range("B2:B" & Slrow), xlAscending, , , , , , xlYes, , False, xlSortColumns, xlPinYin, xlSortNormal

Change the Key1 to the column you want to sort at eg Key1:=Range("B1").
use SortOn:=xlSortOnValues to make sure it sorts on the values not text (I think this does the trick here).
make it recognize headers automatically by using Header:=xlYes (easier).
This should work:
Dim ws As Worksheet
Set ws = ActiveSheet 'better specify Worksheets("SheetName")
With ws.Sort
.SortFields.Clear
.SortFields.Add2 Key:=ws.Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Range("B1:L" & Slrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
If it doesn't work your dates are no date values but text and you need to convert them into date values.
Also it might be a good idea always to use the ISO date format YYYY-MM-DD hh:mm:ss which is the only one that can not be misunderstood by humans and can easily be sorted even as text (eg in file names etc).
Example how it looks sorted with the code above:

Related

How to use indirect reference to select a single cell or range in vba

I need simply a code for selecting a cell, however that cell to select changes. I have a cell in the workbook that will identify what cell it should be. Cell A1 contains the cell # that should be selected.
In this example cell A1 contains the word "P25", so I want the below code to reference A1 for the indirect cell ref to P25, thus select cell P25.
I tried both of these lines separately:
Sub IndirectCellSelect()
Sheet.Range(INDIRECT(A1)).Select
Range(INDIRECT(A1)).Select
End Sub
I get the error Sub or Function is not defined, when it gets to the word INDIRECT
A slight alteration to the posted code works:
Range([indirect("a1")]).Select
but I would advise to try either of these instead:
Sheet.Range(Sheet.Range("A1").Value).Select
Range(Range("A1")).Select
the first being more explicit and is recommended in production code.
You can do this a different way, but if you want to use a native Excel worksheet function within your VBA code, you need to do this like so (note that I have also adjusted how you reference A1):
Application.WorksheetFunction.Indirect(Sheets(1).Range("A1"))
Edit
Apologies - I hadn't test this. It seems that the Indirect function is not available in this context. Instead, try something like this:
Dim rng as Range
Set rng = sheets(1).Range("A1")
sheets(1).Range(rng.text).Select
Worksheets("list").Sort.SortFields.Add Key:=Range(INDIRECT("I16" & "3" & ":" & "I16" & "5002")) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Worksheets("list").Sort
.SetRange Range("B2:K5002")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin

Insert new row and sort automatic in Excel

I have a table in Excel with a list of names linked with some data. I would like to be able to create new rows (with data from something form-alike) and have them sorted into the existing rows.
I don't really know how to code VBA in Excel and can't find any examples that insert rows based on their data. Most examples insert new blank rows to style the table.
I've got this to insert the new row with input value of user:
Sub Test_Function()
Dim val As String
val = InputBox("Enter your name", "May I know your Name!")
'Inserting a Row at at Row 2
Range("A3").EntireRow.Insert
Range("A3").Formula = val
'
End Sub
More information: The data is in this lay-out:
Name - Money Provided W1 - Money ProvidedW2 - Drinks W1 - Drinks W2 - Total Money owed
When entering a new name, the row needs to copy the formulas like the other rows. At the bottom of the sheet is another row with the sum of 'money provided' and 'money owed'. (I think therefore I can't just add it to the last row, but rather insert a new one, not sure tho...)
I wouldn't insert a new row, but rather put the results of the insertion at the end of the sheet:
lastRow = Range("A1").End(xlDown).Row + 1
Range("A" & lastRow) = data1
Range("B" & lastRow) = data2 'etc.
and then sorting the whole sheet by the key you prefer (this example is for sorting A-C in descending order by column A - recorded macro):
Columns("A:C").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1:A" & lastRow), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:C" & lastRow)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

EXCEL VBA Sort after Populating Data

I am new to VBA, and excel macros, but not basic programming. I have a few dozen excel files, that I am taking data from, cleaning it, and populating it into one file. After the data is populated, I'd like to sort it according to Column A. After an 2 hours of playing with it, I just recorded a macro and cut and pasted it into my ButtonCall sub. But I'd like to know why its working and why the solutions I found here, and online would not work for me...
Why does this simple code NOT work:
Set q = ThisWorkbook.Worksheets(2)
LastRow = q.UsedRange.rows.Count 'q.UsedRange.Row ' - 1 + q.UsedRange.rows.Count
LastCol = q.UsedRange.Columns.Count
q.Range("A6:AAA" & LastRow).Sort Key:=q.Columns("A"), Order:=xlDescending
While this modified recorded Macro does?
Set q = ThisWorkbook.Worksheets(2)
LastRow = q.UsedRange.rows.Count 'q.UsedRange.Row ' - 1 + q.UsedRange.rows.Count
LastCol = q.UsedRange.Columns.Count
q.Sort.SortFields.Clear
q.Sort.SortFields.Add Key:=Range("A6:A" & LastRow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With q.Sort
.SetRange Range("A6:AAA" & LastRow)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Any thoughts? Thanks.
Your code is using the range.sort method, while the original code is employing the sort object - two different things.
This code will sort "A6" to end of data by column A, using the Range.Sort method.
Sub MySort()
Dim q As Worksheet
Dim r As Range
Set q = ThisWorkbook.Worksheets(2)
' specify data range from "A6" to end of data
Set r = q.Range("A6", q.Cells.SpecialCells(xlCellTypeLastCell))
' Header:=xlNo assumes A6 row is included in data to be sorted
r.Sort key1:=r(1, 1), Order1:=xlDescending, Header:=xlNo
End Sub

Sorting a table in Excel using VBA?

I have tried to sort a table using the following VBA code. The code does select the correct column, and the column filter does get a small arrow in it, indicating that it is sorted. But the rows do not sort. They stay unsorted.
What is wrong?
Sub SortTableTest()
Dim tbl As ListObject
Dim columnToSortBy As Range
Set tbl = Sheets("PB").ListObjects("AI")
Set columnToSortBy = tbl.ListColumns(9).Range
'Sort table
With tbl.Sort
.SortFields.Clear
.SortFields.Add columnToSortBy, xlDescending
.Header = xlYes
.MatchCase = False
.Apply
End With
End Sub
First, you missed one parameter in .SortFields.Add method. What you need is:
.SortFields.Add columnToSortBy, xlSortOnValues, xlDescending
Second, question from you comment. Try with this kind of References:
Set columnToSortBy = Range(tbl.Name & "[[#All],[column name here]]")

Sort rows by a specific column containing numbers

How to sort rows by a column containing numbers in ascending or descending order?
I know how to sort using Filters and Using Sort function in VBA. But it sorts in alphabetical order only not by numbers.
This is so far I have done.But still the sorting is coming alphabetically.
Sub sortdata()
Dim LastRow As Integer
NoOfRows = Sheets("RawData").Range("A" & Rows.Count).End(xlUp).Row
Sheets("RawData").Rows("2:" & NoOfRows).NumberFormat = "0"
Sheets("RawData").Sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Sheets("RawData").Sort
.SetRange Range("A1:B" & NoOfRows)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
I prefer the Range.Sort method:
[EDIT 2]:
I have added the .TextToColumns line to programmatically address the numbers stored as text issue
Sub sortdata()
Dim ws As Worksheet
Set ws = Sheets("RawData")
With ws.Range("A1:B" & ws.Cells(Rows.Count, "A").End(xlUp).Row)
Intersect(.Cells, ws.Columns("A")).TextToColumns
.Sort Intersect(.Cells, ws.Columns("A")), xlAscending, Header:=xlGuess
End With
End Sub
[EDIT]:
After reading asker's comment:
I will provide an example . If the column A contains this
values:1,2,55,12,14,5343,22222,9 Then after sorting using filter or
inbuilt sort method. The values are sorted as
follows:1,12,14,2,22222,5343,9. But I need the result as follows:
1,2,9,12,14,5334,22222. Is there any in-built function for this?
The problem is that your numbers are stored as text. You'll need to convert them to numbers.
Select column A -> Data -> Text to Columns -> Finish
Now the numbers should sort correctly.