VBA Compile Error: Expected Named Parameter - excel

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

Related

VBA reference to named range

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

How to fix date filter VBA as it is not picking up all dates that fall within my range

I'm trying to create a filter that will filter out all dates that fall within the dates I choose. The dates I choose will always reflect a whole month.
For example, if I need data for May 2019, I will input my start date as 01/05/2019 and my end date as 31/05/2019.
My data filter will need to pick up all rows that go through my start date. So it should pick up whole calendar years (01/01/2019 - 31/12/2019), quarters (01/04/2019 - 30/06/2019) and any dates that cover the month of May.
Currently my filter only picks up whole calendar years and some (but not all)exact dates such as 01/05/2019 - 31/05/2019. So I'm missing a lot of information such as the dates that fall as quarters, or over a number of months surrounding May.
I've attempted to play around with the way that it filters by moving around the less than and more than sign but this just meant that a lot of the deals became excluded.
I use this filter on another workbook with much less data and it picks up all data. Whereas on this workbook, there is much more data and the start dates vary a lot, so I lose about half the data I need.
Sub Filter()
Dim lngStart As Long, lngEnd As Long
lngStart = Range("AI1").Value 'this is the start date
lngEnd = Range("AI2").Value 'this is the end date
Range("G2:G5000").AutoFilter field:=7, _ 'this is the start date column
Criteria1:="<=" & lngEnd, _
Operator:=xlAnd, _
Criteria2:="<=" & lngEnd
Range("H2:H5000").AutoFilter field:=8, _ 'this is the end date column
Criteria1:=">=" & lngStart, _
Operator:=xlAnd, _
Criteria2:=">=" & lngStart
End Sub
I would like all my data that passes through May 2019 (example month) to show when I click on my filter. It is only showing one of the month deals, and one of the quarter deals when there are five more.
Dates are tricky in VBA filters. For one thing, the VBA Date data type is not quite the same as an Excel value formatted as a date.
And I think your logic was a bit off also.
This seems to work on your sample data.
Sub Filter()
Dim lngStart As Long, lngEnd As Long, fltrRng As Range
lngStart = Range("J1").Value 'this is the start date
lngEnd = Range("J2").Value 'this is the end date
Set fltrRng = Range("A2:H5000")
With fltrRng
.AutoFilter field:=7, _
Criteria1:=">=" & CDbl(lngStart)
.AutoFilter field:=8, _
Criteria1:="<" & CDbl(lngEnd)
End With
End Sub
Note that we defined the entire filter range, but I would define it differently, and dynamically, so as not to encompass more rows than necessary.
With Worksheets("sheet1")
Set fltrRng = .Range(.Cells(1, 1), .Cells(.Rows.Count, 8).End(xlUp))
End With
Also, we converted the lngStart and lngEnd to the Double data type, which is how dates are stored in Excel on the worksheet. You could have just declared them as being of type Double. So, with all that:
Sub Filter()
Dim lngStart As Double, lngEnd As Double, fltrRng As Range
lngStart = Range("J1").Value 'this is the start date
lngEnd = Range("J2").Value 'this is the end date
With Worksheets("sheet1")
Set fltrRng = .Range(.Cells(1, 1), .Cells(.Rows.Count, 8).End(xlUp))
End With
With fltrRng
.AutoFilter field:=7, _
Criteria1:=">=" & lngStart
.AutoFilter field:=8, _
Criteria1:="<" & lngEnd
End With
End Sub
Finally, the logic should state, I believe, that you want dates where
the start column is equal or greater than the start date AND
the end column is less than the end date (which, you have entered as one date past the actual desired end date, which is proper.
EDIT:
Another problem is that some of your dates are not "real Excel dates". In other words, they are textual representations of dates in a format that is different from your regional windows settings, where the Month entry is > 12.
This problem usually arises when a text or csv file is OPEN'd, rather than IMPORT'd, and the date format in the file is different from the date format in the Windows Regional Settings for the computer.
By IMPORTing a csv file, one can specify the date format of the incoming data and avoid this problem.
To demonstrate it in the file you provided, change the filtering part of the macro to also pick up text dates. eg:
With fltrRng
.AutoFilter field:=7, _
Criteria1:=">=" & lngStart, _
Operator:=xlOr, _
Criteria2:=Format(lngStart, """*""/mm/yyyy")
.AutoFilter field:=8, _
Criteria1:="<" & lngEnd, _
Operator:=xlOr, _
Criteria2:=Format(lngEnd - 1, """*""/mm/yyyy")
End With
However, this is far from ideal because, most likely, even the dates that are rendered as "real Excel dates" were probably translated incorrectly. In other words, if the CSV file contained 05/01/2019 meaning 5-Jan-2019, it would be translated to 1-May-2019 in the scenario cited.

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 for filtering columns

I have a big database-like sheet, first row contains headers. I would like a subset of rows of this table based on column values. Two issues:
1) VBA-wise I would like to loop through the columns, when the values for all necessary columns all match, copy the entire row into a new sheet.
2) The subset of rows is based on a list. I just read I can use Autofilter with an array. Is it possible to input this array from a column instead of manually entering it in the VBA code? The list I'm using consists of 200 different strings and will be updated periodically.
Where CritList is the list of strings. I still need to figure out how, but now I leave the office, so more tomorrow.
EDIT1 Thanks to #DougGlancy; the autofiltering works now. Here is his beautiful code (I only added the array-filter).
EDIT2 Included a more elaborate array-filter, where NameList is the list I would like to filter for. Now it all works!
Sub FilterAndCopy()
Dim LastRow As Long
Dim vName As Variant
Dim rngName As Range
Set rngName = Sheets("Sheet3").Range("NameList")
vName = rngName.Value
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("A:E").AutoFilter
'Array filter from NameList
.Range("A:J").AutoFilter Field:=3, Criteria1:=Application.Transpose(vName), _
Operator:=xlFilterValues
.Range("A:E").AutoFilter field:=2, Criteria1:="=String1" _
, Operator:=xlOr, Criteria2:="=string2"
.Range("A:E").AutoFilter field:=3, Criteria1:=">0", _
.Range("A:E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

excel vba autofilter not filtering on dates

I have column of dates, which is an output from a database. There is a macro that filters on this date which is meant to show all dates older than 14 days from current date excluding nulls. The filter when applied filters the entire sheet and shows nothing. When I take off the - 14 I do get dates, I have tried even using alt a, e, f to ensure that the column is the correct format, but no luck.
Here is my code snippet:
ActiveSheet.UsedRange.AutoFilter Field:=34, Criteria:="<>NULL", _
Operator:=xlAnd, Criteria2:="<" & Now()-14
I have tried changing the criteria2 to "<" & Date - 14 & "# 00:00:00 AM#"
Please help
Try this
Change Criteria:="<>NULL" to Criteria1:="<>NULL"
FOLLOWUP
The code was not working as the headings were in not in Row 1. Once the exact range was specified, it started working.
Option Explicit
Sub Sample()
Dim lRow As Long
lRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
ActiveSheet.AutoFilterMode = False
ActiveSheet.Range("$A$2:$BV$" & lRow).AutoFilter Field:=34, Criteria1:="<>NULL" _
, Operator:=xlAnd, Criteria2:="<" & Format(Date - 14, "0")
End Sub

Resources