VBA reference to named range - excel

I have following code in which I have tried to applied 3 filters, now what I want is, to apply this filter criteria based on named range
I have stored relevant value in specific cell and given names to that range
for first criteria i.e. >=200 named range is VOLUME
for second criteria i.e. >=0.07 named range is MOVE
for third criteria i.e. >=400 named range is STRENTH
So what are the changes that I need to make in following code?
Sub FILTER2()
'FILTER CRITERIA
ActiveSheet.Range("$A$2:$AC$500").AutoFilter Field:=6, Criteria1:=">=200", _
Operator:=xlAnd
ActiveSheet.Range("$A$2:$AC$500").AutoFilter Field:=21, Criteria1:=">=0.07" _
, Operator:=xlAnd
ActiveSheet.Range("$A$2:$AC$500").AutoFilter Field:=28, Criteria1:=">=400" _
, Operator:=xlAnd
Range("A1").Select
End Sub

As per my comment, you might want to consider a With statement, better not to refer to ActiveSheet
Sub FILTER2()
With Sheet1 'Change according to your sheets CodeName
.Range("$A$2:$AC$500").AutoFilter 6, ">=" & .Range("VOLUME")
.Range("$A$2:$AC$500").AutoFilter 21, ">=" & .Range("MOVE")
.Range("$A$2:$AC$500").AutoFilter 28, ">=" & .Range("STRENTH")
End With
End Sub

you can try defining a variable to contain the value of your named range.
Named Range in your sheet as "Volume" then i can store that value in var namedRange1.
example below:
Sub FILTER2()
namedRange1 = range("Volume")
'FILTER CRITERIA
ActiveSheet.range("$A$2:$AC$500").AutoFilter Field:=6, Criteria1:=">=" & namedRange1, _
Operator:=xlAnd
....same with the other lines, just define new variable to contain new named range

Related

Sort two data ranges in excel without affecting the first sort

I've got an active table with regularly changing data. Id like to sort column "I" (dates)for all blank values to be at the top.
Next, Id like all of the data under my blank values in "I" to then be sorted in column "J" as ascending.
Ideally, this means that my data will show all blank cells in column "I", and then everything under my last blank cell will then be sorted using column "J" (ascending).
(if I were to run my sort on column "J" after my sort on "I". My blank rows will be mixed into the data THIS IS NOT WHAT I WANT)
I need to find a way to ONLY sort my rows under my last blank cell in column "I".
Unfortunatley, this is only as far as I have got
Range("I:I").Sort Key1:=Range("J:J"), _
Order1:=xlAscending, _
Header:=xlYes
If you have any questions, please ask.
Thank you very much,
Matt
e.g.
If I understand you correctly, the sub below is not directly answer to your question, but maybe can help you to get started.
Sub test()
Dim rg As Range: Dim oldDt
'set range of the data/table (include header) into rg variable,
'(change the range as needed)
Set rg = Range("A1:C28")
'make an old date into oldDt variable
oldDt = "1-jan-1964"
'fill the rg column which row is blank with old date.
'(change the column number as needed)
rg.Columns(1).SpecialCells(xlBlanks).Value = oldDt
'perform two level sort,
'(change the column number as needed)
With ActiveSheet.Sort
.SortFields.Add Key:=rg.Columns(1).Resize(1, 1), Order:=xlAscending
.SortFields.Add Key:=rg.Columns(2).Resize(1, 1), Order:=xlAscending
.SetRange rg
.Header = xlYes
.Apply
End With
'format the date in the column into general,
'replace oldDt with blank,
'then bring back the expected date format,
'(change the column number as needed)
With rg.Columns(1)
.NumberFormat = general
.Replace What:=CDbl(CDate(oldDt)), Replacement:=""
.NumberFormat = "dd-mmm-yy"
End With
End Sub
Before run the sub:
After run the sub:

Autofilter parts of multiple arguments

I'm trying to use the AutoFilter function in VBA.
I have cells in this column filled with values that start with a value that I want to filter on like "pathogenic", "polymorfism", "VUS",... but ends with some more text that I don't want to use in the filter.
e.g.
variant
class
V600E
pathogenic variant - BRAF
V590A
VUS - D1234567
G12D
pathogenic variant - KRAS
G15A
polymorfism
A56D
polymorfism - KFP
E4654M
presumably pathogenic variant
In this case I want to filter all rows where the class starts with "pathogenic variant","VUS" and "presumably pathogenic variant", in the example row 1-3 and row 6.
I found a way to use the autofilter for 2 values:
ActiveSheet.Range("$A$2:$BB$550").AutoFilter _
Field:=17, _
Criteria1:=("=patho*"), _
Operator:=xlOr, _
Criteria2:=("=VUS*"), _
Operator:=xlFilterValues
I can't use more then 2 criteria. When I use the following code the filtering doesn't work.
ActiveSheet.Range("$A$2:$BB$550").AutoFilter _
Field:=17, _
Criteria1:=Array("=patho*", "=VUS*", "=presumably patho*"), _
Operator:=xlFilterValues
You can use Advanced Filter.
Columns A and B: Your range
Column D: Criteria
Column F and G: Extract
You you want to Filter in Place instead of using Copy uncomment the last line.
Sub AdvFilter()
Dim yourRange As Range
Dim criteriaRange As Range
Dim extractRange As Range
Set yourRange = Range("A1:B25")
Set criteriaRange = Range("D1:D4")
Set extractRange = Range("F1:G1")
' Advanced filter: Copy
yourRange.AdvancedFilter Action:=xlFilterCopy, criteriaRange:=criteriaRange, CopyToRange:=extractRange, Unique:=False
' Advanced filter: Filter in Place
'yourRange.AdvancedFilter Action:=xlFilterInPlace, criteriaRange:=criteriaRange, CopyToRange:=extractRange, Unique:=False
End Sub

Range Column and add Value to the specific range

I have Excel file that I want to filter about one column and on another column add specific value
Sub Macro1()
'
' Macro1
'
'
Range("Table1[type phone]").Select
ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
"=*samsung*", Operator:=xlAnd
Range("Table1[company]").Select
'Here I want to add the specific value "Samsung"'
ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
"=*iphone*", Operator:=xlAnd
Range("Table1[company]").Select
'Here I want to add the specific value "Apple"'
End Sub
Also how can I filter about one column Blanks cells and on another column add specific value "other"?
[
What conditions can be written if, for example, the Samsung Devices table is missing?
Because if I run the code it crashes in the line it is looking for Samsung.
How can I do it?
Thank You for helping!
To change the value of only cells that are visible (aka those that are show in the filter) you can use SpecialCells(xlCellTypeVisible)
So for your example the code that would go in the first break would be
"Range("B2:B18").SpecialCells(xlCellTypeVisible).Value= "Samsung"
and the second break
"Range("B2:B18").SpecialCells(xlCellTypeVisible).Value= "Apple"
You need to change "18" to whatever the last row is. (Or you can define a variable called LastRow and then call that instead of hard-coding the number which means it will dynamically change based on how many rows there are.)
With LastRow
Sub Macro1()
Dim LastRow As Long
LastRow = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
Range("Table1[type phone]").Select
ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
"=*samsung*", Operator:=xlAnd
Range("Table1[company]").Select
Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible).Value= "Samsung"
ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:= _
"=*iphone*", Operator:=xlAnd
Range("Table1[company]").Select
Range("B2:B" & LastRow).SpecialCells(xlCellTypeVisible).Value= "Apple"
End Sub
We created a new variable called LastRow and defined it as long (A type of number). Then we defined LastRow according to a formula I use from this site:
https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba
Finally we replace Range("B2:B18") with Range("B2:B" & LastRow) which dynamically replaces the 18 with the number LastRow.

VBA AutoFiltering using multiple variable

I have a problem using my autofilter. I need to filter sever values at a time.
I have the list of values on first sheet (column I2:I50) and on the second sheet I would need to filter all these values from database.
My code so far is:
Dim OZ As Variant
OZ = Array("100001", "100015")
Sheets("Sheet2").Select
Range("A1:M1").AutoFilter Field:=3, Criteria1:=OZ, _
Operator:=xlFilterValues
This works perfectly so far. Now I am strugeling to setup the macro in a way, so the array refers to the Range of Sheet1 and I2:I50. Values in this range are variables calculated by functions.
Can you please help me with that?.
Thanks
This For would set your OZ variable with all the 49 values from Sheet1
'You need 49 values I2:I50
Dim OZ(49) As Variant
For i = 0 To 48
'1st data row starts at I2, hence + 2
OZ(i) = "=" & Worksheets("Sheet1").Range("I" & i + 2).Value
Next i
Worksheets("Sheet2").Range("A1:M1").AutoFilter Field:=3, Criteria1:=OZ, Operator:=xlFilterValues
you could use Join() and Split() functions to return a Variant array compatible for Criteria1
Dim OZ As Variant
OZ = Split(Join(Application.Transpose(Worksheets("Sheet1").Range("I2:I50").Value), "|"), "|")
Worksheets("Sheet2").Select
Range("A1:M1").AutoFilter Field:=3, _
Criteria1:=OZ, _
Operator:=xlFilterValues
but you should avoid the Select/Selection/Activate/ActiveXXX pattern and use explicitly fully qualified range references
Worksheets("Sheet2").Range("A1:M1").AutoFilter Field:=3, _
Criteria1:=Split(Join(Application.Transpose(Worksheets("Sheet1").Range("I2:I50").Value), "|"), "|"), _
Operator:=xlFilterValues
i think that advanced filter will do the job.
Sub ExampleCopy()
Sheets("Table").Range("A1:B7").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Cryteria").Range("A1:15"), _
CopyToRange:=Sheets("Result").Range("A1"), _
Unique:=False
Sheets("Result").Select
End Sub
'OR
Sub ExampleInPlace()
Sheets("Table").Range("A1:A11").AdvancedFilter Action:=xlFilterInPlace _
, CriteriaRange:=Sheets("Cryteria").Range("A1:A6"), Unique:=False
End Sub
The first one will copy result to a custom location. In this case to Sheet "Result" cell A1.
The second one will filter in place so in sheet "Table"
Bear in mind that in order for this to work your cryteria column header has to be the same as the data table column.
You can aslo try recording this macro using "advanced" from ribbon tab "DATA" section "Sort&filter".
Good luck.
The range can be evaluated to an array:
[Sheet2!A1:M1].AutoFilter 3, [transpose(text(Sheet1!I2:I50, "#"))], xlFilterValues

VBA Compile Error: Expected Named Parameter

I am new to VBA's and have pieced together this macro from various searches on "how to filter between two specific dates in excel." I am trying to have it read the dates from two cells and restrict the shown data to data between those dates. The input data to the workbook is a SQL table that will be growing over time, so I need the left bound of the range to be the last row with a value in it. Each line in my AutoFilter part returns an "Expected Named Parameter" error with the := sign highlighted. From the forums I have read this is due to using VBA reserved words as variable names, but I not think that is the case in this instance.
Here is my code:
Public Sub MyFilter()
.AutoFilterMode = False
Dim datRight, datLeft As Date
Dim lastRow As Long
datLeft = Range("J1").Value
datRight = Range("J2").Value
lastRow = Range("A:A").Find("*", Range("A2"), searchdirection:=xlPrevious).Row
ActiveSheet.Range("F2:F" & lastRow).AutoFilter Field:=7,
Criteria1:=">=" & datLeft, _
Operator:= xlAnd,
Criteria2:="<=" & datRight, VisibleDropDown:=True
End Sub
The first error you will get is at the line .AutoFilterMode = False Notice the DOT before Autofilter. You have to qualify it with the relevant sheet. For example, ThisWorkbook.Sheets("Sheet1").AutoFilterMode = False
When you are trying to find the lastrow using *, Always use the method as mentioned in THIS post else you will get an error if the worksheet is blank.
Your declaration Dim datRight, datLeft As Date. In VBA only the last variable will be declared as Date and the first one will be declared as Variant. Change it to Dim datRight As Date, datLeft As Date Also if the J1 and J2 values are not date values then you will get an error.
Now to your problem. You are getting that error because you the missing the continuation character _
Try this
ActiveSheet.Range("F2:F" & lastRow).AutoFilter Field:=7, _
Criteria1:=">=" & datLeft, _
Operator:=xlAnd, _
Criteria2:="<=" & datRight, VisibleDropDown:=True

Resources