Excel Vba Sort Date in MMM format - sorting

I have some columns of dates in the format of MMM-DD-YYYY for example Jan-03-2014 but when I sort it using:
ActiveSheet.Range("A3:Z" & rowNum).Sort Key1:=ActiveSheet.Columns("E")
It doesn't sort by real date. I realized its treating it like strings and sorting them based on first letter. Is there anyway to sort it by real date?
Thanks

You can do this by recording a macro in Excel, it give me something like that and sort dates in the format of "MMM-DD-YYYY"
ActiveWorkbook.Worksheets("Feuil1").Sort.SortFields.Add Key:=Range("A1:C1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"janvier,février,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décemb re" _
, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Feuil1").Sort
.SetRange Range("A1:C1")
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With

So based on suggestions from John, to sort dates in MMM format I would need to create a new column, make it a date and sort it based on that column, I used the code below:
For i = 3 To rowNum
If ActiveSheet.Cells(i, 5).Value <> vbNullString Then
ActiveSheet.Cells(i, 8).Value = CDate(ActiveSheet.Cells(i, 5).Value)
End If
Next i
ActiveSheet.Range("A3:Z" & rowNum).sort Key1:=ActiveSheet.Columns("H"), Header:=xlNo
ActiveSheet.Columns("H").Delete
Just thought I should share it, Thanks a lot!

Related

Converting Time-Stamp String to Another Date Format in VBScript

I have datetime stamp (MMDDYYYYHHMMSS) extracted from a file Name as
Filedate = "10212015140108"
How can I convert it into datetime format mm/dd/yyyy hh:mm:ss.
Can someone help to get it resolved?
From what I can gather from the question it looks as though the Filedate value is just a string representation of date (mmddyyyyhhnnss), with that in mind did a quick test to see if I could parse it into the format required.
There are other ways of approaching this like using a RegExp object to build up a list of matches then use those to build the output.
Worth noting that this example will only work if the structured string is always in the same order and the same number of characters.
Function ParseTimeStamp(ts)
Dim df(5), bk, ds, i
'Holds the map to show how the string breaks down, each element
'is the length of the given part of the timestamp.
bk = Array(2,2,4,2,2,2)
pos = 1
For i = 0 To UBound(bk)
df(i) = Mid(ts, pos, bk(i))
pos = pos + bk(i)
Next
'Once we have all the parts stitch them back together.
'Use the mm/dd/yyyy hh:nn:ss format
ds = df(0) & "/" & df(1) & "/" & df(2) & " " & df(3) & ":" & df(4) & ":" & df(5)
ParseTimeStamp = ds
End Function
Dim Filedate, parsedDate
Filedate = "10212015140108"
parsedDate = ParseTimeStamp(FileDate)
WScript.Echo parsedDate
Output:
10/21/2015 14:01:08

not able to format results in Dateadd

Function CurrMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 0, dateval)
CurrMonthName = MonthName(Month(tmp))
CurrMonthName = replace(CurrMonthName , "%M",CurrMonthName)
i am trying to format the month name so that it displays first 3 letters. On searching found %M can be used. I tried using it in above code and results are not coming as expected. It is still displaying full month
In VBScript, the way to get an abreviated Monthname is MonthName.
>> WScript.Echo MonthName(Month(Date()), True)
>>
Jul
>>
See this answer for a more flexible way to format dates (and other kind of data).
Use the function "Left" to cut the first off: Left("February",3) gives you "Feb"

How to Sort Excel Column S.T. Rows w/ Null/Empty Column Cell Go On Top?

I have several rows that have data and 'flags' that are raised adjacent to the data when a macro is run.
For example:
First Name | Last Name | Flag
John | Smith | Needs a Bath
Cindy | LuWho |
Bob | Loblaw | Needs a Bath
Goal:
I want the rows w/o flags (ie where column C == NULL/Empty string) to be sorted to the top and then sort by column B by A->Z to get this:
Cindy | LuWho | Bob | Loblaw | Needs a Bath John | Smith |
Needs a Bath
What I've Tried:
Using Excel 2007's 'Sort', I've done Sort By (Column C), Sort On (Values) Sort By (A to Z) and (Z to A). Both A to Z and Z to A result in the flagged rows on top, not the bottom.
Before:
After:
I ultimately want the code, but I'm currently trying to figure out how to do it by hand so I can then get the code through Excel's 'Record Macro'.
Per my comment above, the problem is that you are using a formula that evaluates to an empty string. If the field was actually empty, you'd have the behavior you are looking for.
Here's a dirty-but-it-works approach:
Make a new column to the right. Use the formula =IF(C2<>"",2,1) and fill down.
Hide the column from prying eyes (just right-click on the grey column header at top to hide it)
Sort by this column instead of C.
I ended coming up with a solution that IMO, is more elegant than #Poweruser 's creating another column, populating it, hiding it, and then using sort on the hidden column. My method utilizes font color changes based on conditional formatting and sorts off of that.
Select desired range of column that contains blank values you want to sort by
Use Conditional Formatting>New Rule>'Use a formula to determine which cells to format' and in the textbox use the formula =IF(INDIRECT("RC",0)="",TRUE,FALSE)
Select 'Format...', select 'Font' tab and change the Font color to something not black or 'Automatic', apply changes
Using 'Sort', have 'Sort By' be the column with the blank cells, 'Sort On' be 'Font Color', and for 'Order By' change Automatic to whatever color you selected and have it be 'On Top'
With a little bit of tinkering of the recorded macro, I got the following working code (which also sorts by value another column after sorting for the 'blank' cells):
For oRow = 2 To iFinalRow
ActiveWorkbook.ActiveSheet.Cells(oRow, 5).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF(INDIRECT(""RC"",0)="""",TRUE,FALSE)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.ThemeColor = xlThemeColorLight2
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Next oRow
'Sort
ActiveWorkbook.ActiveSheet.SORT.SortFields.Clear
ActiveWorkbook.ActiveSheet.SORT.SortFields.Add(Range("E:E"), _
xlSortOnFontColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(31, 73, 125)
ActiveWorkbook.ActiveSheet.SORT.SortFields.Add _
Key:=Range("D1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
With ActiveWorkbook.ActiveSheet.SORT
.SetRange Range("A:F")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
One of the solutions is to replace blanks with single quote (') before sorting. It is not visible but it is not NULL. See the code example:
Public Sub Sort_blanks()
Dim lastrow As Integer
' The number of the last row
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
' Replace blanks with with single quote
Range("C2:C" & lastrow).Select
Application.DisplayAlerts = False
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "'"
Application.DisplayAlerts = True
On Error GoTo 0
' Sort
Range("A:C").Sort key1:=Range("C:C"), key2:=Range("B:B"), _
order1:=xlAscending, order2:=xlAscending, Header:=xlYes
End Sub

Sorting range in ascending numerical order containing strings by vba excel

i have a range containing the following strings:
step_1, step_10, step_3, step_2
using the following code
input_sh.Activate
With ActiveSheet
.Range("H2:H20").Select
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=Range("H2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers 'xlSortNormal
With .Sort
.SetRange Range("H2:H20")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
step_10, step_1, step_2, step_3
but i would like to get
step_1, step_2,step_3,step_10
I would separate the number into another column, your last + 1, using mid function and sort on that.
Edit: I'm not at my pc but I think your only way to do this is to setup a macro that:
Filter your sheet by the first 9.
Cut and insert them before row 2.
Sort these on their own.
Then remove the filter and sort the rest as you have above.
Your strings have underscore followed by numbers. if that is going to be format of your string you can simply split your string using convert text to columns using "_" as your delimiter. Later you can sort and concatenate to get your sorted list of strings.
Sub Sample()
Columns(1).Copy Columns(3)
Columns("C:C").Select
Selection.TextToColumns Destination:=Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, Other:=True, OtherChar:="_", FieldInfo:=Array(Array(1, 1), Array(2, 1))
Columns("D:D").Sort Range("D1")
i = 1
Do While Not IsEmpty(Range("C" & i))
Range("B" & i) = Range("C" & i) & "_" & Range("D" & i)
i = i + 1
Loop
End Sub
thanks every one for you contribution.
to user I found my solution before reading your suggestion. thanks anyway for your effort
my solution:
split str for "_"
write 2nd index next to filenames order 2nd cols by then col with only number
clean col with numbers

VBScript Help: Split? Replace?

Im working on a vbscript that is pulling data from excel to text. I currently have a column in an excel sheet with values like:
305 ABCDE
23 FTPXX
N3 TOY
3321 APPLE
I want to get the 2nd values to only show so that the data would look like
ABCDE
FTPXX
TOY
APPLE
I was thinking of trying to split the values and then replacing the first part of the value as "spaces" and just trimming the results.
Can someone help me with this or know a better way to do this?
Thanks in advance.
s1 = "305 ABCDE 23 FTPXX N3 TOY 3321 APPLE"
s2 = Split(s1, " ")
For i = 0 To UBound(s2) Step 2
s2(i) = " "
Next
s3 = trim(Join(s2, ""))
WScript.Echo s3
set myregexp = new RegExp
myregexp.IgnoreCase = True
myRegExp.Global = True
myRegExp.Pattern = "([a-zA-Z]+)"
Set myMatches = myRegExp.Execute(subjectString)
myMatches will hold any matches found within subjectString

Resources