Sort multiple columns by one column - vba

I'm making an email list in Excel with three columns. On the worksheet, I have two buttons, "sort by Name" and "sort by Date added". I would like to sort all three columns by the button chosen so I can find entries faster (I am also entering a separate lookup function later).
Basically, I want the sort function that's already on the toolbar in the worksheet where you can just press it and it knows which column to sort by already. I've seen things for macros and for VBA but all of them are sorting columns by separate parameters, whereas I need these columns linked.

The code produce by the recorder on a Range.Sort method is very verbose and can be chopped down quite a bit to what is essential.
If columns A:C were Name, Email, Date Added then this will sort by Name first, then Date Added.
with worksheets("sheet1") '<~~ set this properly!
with .cells(1, 1).currentregion '<~~ assumes data starts in A2 with a header row in A1:C1
.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
Key2:=.Columns(3), Order2:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
end with
end with
This will sort by Date Added first, then Name.
with worksheets("sheet1") '<~~ set this properly!
with .cells(1, 1).currentregion '<~~ assumes data starts in A2 with a header row in A1:C1
.Cells.Sort Key1:=.Columns(3), Order1:=xlAscending, _
Key2:=.Columns(1), Order2:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
end with
end with
You can have up to 3 keys. Any more than that and you have to run the routine twice. The opposite of xlAscending is of course xlDescending.

The best way I've found to find something that's already on the toolbar is to use the "Macro Recorder" in a blank/new workbook, and then look at the code.
Are the columns adjacent to each other? Because if so you can use something like this;
//Alright, so this is if you wanted each of the columns to have their
//own values that you are sorting by, if you just want one criteria,
//just use one of the lines
Dim varName as String
Dim varDate as String
Dim varExtra as String
ActiveSheet.Range("A:C").AutoFilter Field:=1, Criteria1:=varName
ActiveSheet.Range("A:C").AutoFilter Field:=2, Criteria1:=varDate
ActiveSheet.Range("A:C").AutoFilter Field:=3, Criteria1:=varExtra
Basically, it's saying for the three columns given, go find the field (which will correspond to a column) indicated and filter by the criteria. You can also use a string value in the Criteria spot instead of a variable.

Related

VBA Macros How to put in date order then numerical order?

Just as the title says, how can I put an excel sheet in date order, then numerical order? I know how to do these things separately, but the problem is, is that I need it to stay in date order and THEN be in numerical order. Once I put it in numerical order, the dates become mixed up again. The Date is in Column A while the data is in Column B.
Try,
with worksheets("sheet1")
.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
Key2:=.Columns(2), Order2:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlyes
end with
Use the Sort option from the Data menu

How to filter multiple data using keywords in VBA?

I want to filter out the unnecessary data with these 3 keywords: Proton, Hyundai, Perodua. But I am getting the "Named argument not found" error after I run this code.
''Filtering return reason for Sheet1
Rows("1:1").Select
Selection.AutoFilter
Dim rng As Range
Set rng = ActiveSheet.Range("A1:L2671")
FilterField = WorksheetFunction.Match("Car", rng.Rows(1), 0)
'Turn on filter if not already turned on
If ActiveSheet.AutoFilterMode = False Then rng.AutoFilter
'Filter Specific Countries
rng.AutoFilter Field:=FilterField, Criteria1:="=*Proton*" _
, Operator:=xlOr, Criteria2:="=*Hyundai*" _
, Operator:=xlOr, Criteria3:="=*Perodua*"
The Criteria3 was highlighted after I ran this code. Why can't I insert the 3 criteria onto the filter filed?
Here's the example of my data:
I am not sure if autofilter can take more than 2 criteria as given in MSDN article
However, you may want to try passing an array into criteria1 as proposed in another solution here
Personally, I would prefer to use helper columns with functions (e.g. if statements) to narrow down my selection before using autofilter.
The problem occurs because of using Wildcards. In those cases you can not use more than 2 filter values at the same time.
This doesn't work:
rng.AutoFilter Field:=FilterField, _
Criteria1:=Array("*Hyundai*","*Proton*","*Perodua*"), _
Operator:=xlFilterValues
However, you could use pattern matching by first getting your range to be filtered in an array and dynamically create the values to be filtered array.
Good sample code is in this answer

Excel 2010 Filter by string to prevent them being deleted by remove duplicates

I have a list and sometimes there are duplicated things that normally get removed with remove duplicates no problem. This time I found I have a common used string and don't want any of these strings to get deleted in case they are have the same amount. the code goes like
Dim Rng As Range
Dim Rw As Long
Rw = Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.AutoFilterMode = False
Set Rng = Range("A3:K" & Rw)
With Rng
.AutoFilter
.AutoFilter Field:=1, Criteria1:="<>*Discount*", Operator:=xlAnd
End With
ActiveSheet.Range("$A$1:$C$1000").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
ActiveSheet.AutoFilterMode = False
This code hides "Discount" but when it removes duplicates it skips the filter and deletes them anyways. from the data shown to excel they are exactly the same but the data comes from QuickBooks and I need all the discounts to make everything add up properly.
One method:
Sort the data putting Discounts at the beginning or end.
Filter the data hiding the Discounts.
Use Selection.SpecialCells(xlCellTypeVisible).Select to select everything NOT
a discount.
Remove duplicates from the selected range.
Remove duplicates and Sort do not work on multiple ranges so getting the discounts in one block and not selecting them is important.

Excel macro - keeping lines with highest priority weight

I have an excel document that has the following column data:
Country,AnimalName,Year,ResultsQuality(1-6),ResultA,ResultB,ResultC.....ResultZ
ResultQuality is an indicator of how accurate the result in the line (ResultA-ResultZ), the highest quality is ResultsQuality=1, the lesser quality level is ResultsQuality=6.
Here is some rows examples:
row#1: US,Camel,1985,2,111,222,333.....999
row#2: US,Camel,1985,5,114,227,338.....958
row#3: CANADA,Camel,1985,3,214,257,638.....858
row#4: CANADA,Shark,1985,1,14,27,38.....8
row#5: CANADA,Shark,1985,2,14,257,3.....628
row#6: CANADA,Shark,1985,4,14,25,63.....568
row#7: CANADA,Shark,1985,6,14,25,6.....838
As you see, the [Country,AnimalName,Year] key can contain one or more lines that has different resultQuality in it.
The macro should:
Go through all the lines, and for each [Country,AnimalName,Year] key - keep the highest quality results line. The other less quality rows for that [Country,AnimalName,Year] should be removed.
After running the macro on the 3 rows above - the results should be:
row#1: US,Camel,1985,2,111,222,333.....999
row#2: CANADA,Camel,1985,3,214,257,638.....858
row#3: CANADA,Shark,1985,1,14,27,38.....8
Thanks allot!
This can actually be accomplished without declaring a single variable. Removing duplicates works from the bottom to the top so if the data is correctly sorted and the appropriate columns supplied to determine duplication, the operation should be dead easy.
Sub Highest_Priority_Weight()
With ActiveSheet.Cells(1, 1).CurrentRegion
'this method can only use three key columns on a sort so we do it twice
.Cells.Sort Key1:=.Columns(4), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
Key2:=.Columns(2), Order2:=xlAscending, _
Key3:=.Columns(3), Order3:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
'now that the best are at the top, dedupe to clear all others
.RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xlYes
End With
End Sub
That should turn this,
    
.. into something like this,
    
For Excel, that's the quickest way I know of. A subsequent sorting routine could be added after the .RemoveDuplicates operation if you prefer some other displayed format.

excel vba sorting currency column descending

I have a sheet with 2 columns A has shopnames and B has currency values
I want to sort in descending order column B
Here's what I have done:
With Sheets("helpsheet")
.Sort Key1:=Range("A"), Order1:=xlDescending, Header:=xlYes
End With
It doesn't work. What do I have to do differently?
There are some options of sorting available in VBA. The simplest way to improve you code is to add a range of data which you want to sort. Therefore you need to improve your code to the following:
With Sheets("helpsheet").Range("a1").CurrentRegion
.Sort Key1:=Range("B1"), Order1:=xlDescending, Header:=xlYes
End With
What I did:
assumed that your data range starts in Range("A1") and makes a region (therefore I used CurrentRegion property in With line.
I set sorting key to Range("B1") according to information from your question.
If required you could change these points accordingly to your situation.