Skip code when filters applied and returns no results VBA - vba

I am using the below code to filter data as part of a much larger code however in some cases there may not be any results returned when the filters are applied. Alternatively If no results are returned I would like to skip part of the code.
Can anyone suggest the code I would need to use for this. (I'm guessing it would be an IF statement but unsure)
The code I am currently using is
Worksheets("DC Allocations Input").Activate
ActiveSheet.Unprotect Password:="Projects123"
ActiveSheet.Range("$B$9:$CT$382").AutoFilter Field:=1, Criteria1:="<>"
ActiveSheet.Range("$B$9:$CT$382").AutoFilter Field:=5, Criteria1:="=OPP", Operator:=xlOr, Criteria2:="=RSK"
ActiveSheet.Range("$B$9:$CT$382").AutoFilter Field:=6, Criteria1:="<>"
Any help would be much appreciated.
Thanks

You can use an if statement with special cells visible like this:
Dim lngCnt As Long
On Error GoTo someplace 'you get an error if there are no visible cells, use it to skip to where you want
lngCnt = Range("$b$10:$CT$382").SpecialCells(xlCellTypeVisible).Count 'Note I'm not including the headings row, this will always be visible
On Error GoTo 0
'Put your code to run if there are results from the filter here
someplace:
'And the code you want to resume at here

Related

Autofill in Excel VBA returns error 1004

I am trying to get a raw Excel file into a customized format. I added a picture below, so its easier to explain. I will address the requirements as steps too.
1) I need to get rid off all columns which include "Importo" or "Prezzo"
2) I need to extract the date from the remaining columns (Quantitá). First, I insert an empty row on top and then i apply right(cell,7).
So far, so good.
Then I want to autofill the remaining columns, but i get a 1004 error. In the example code I tried from J:O, but really id need it from J to the last column. I post the code (which works until the last row).
I was actually wondering if Autofilling is best practise here, maybe indexing though would be better?
Sub delete_col()
Dim A As Range
Do
Set A = Rows(1).Find(What:="Importo", LookIn:=xlValues, lookat:=xlPart)
If A Is Nothing Then Exit Do
A.EntireColumn.Delete
Loop
Do
Set A = Rows(1).Find(What:="Prezzo", LookIn:=xlValues, lookat:=xlPart)
If A Is Nothing Then Exit Do
A.EntireColumn.Delete
Loop
Rows("1:1").Select
ActiveCell.EntireRow.Insert
ActiveCell.Range("J1").Select
ActiveCell.FormulaR1C1 = "=RIGHT(R\[1\]C,7)"
Selection.AutoFill Destination:=ActiveCell.Range("J1:O1"), Type:=xlFillDefault
End Sub
I suppose that in the line ActiveCell.FormulaR1C1 = "=RIGHT(R\[1\]C,7)", the \ is a kind of typo, which should be deleted.
Concerning the 1004 error, the easiest way to go around it, while doing AutoFill, is something like this:
Sub TestMe()
Range("A1:O1") = Range("J1")
End Sub
Thus, every value in Range("A1:O1") will be set with the value from Range("J1").
However, your code uses a lot of Select, Activate and ActiveCell. Try to avoid these, because they are not considered good practices in VBA and may lead to different errors. How to avoid using Select in Excel VBA

Deleting Rows From Filtered Range Via Macro

I am having issues with the below code, which is trying to filter a set of data, then delete the visible rows. Currently I get a "Run Time 1004 Error: Delete Method or Range Class Failed" which occurs on the last line of my code. I found a similar question on the site, and the answer appears to be exactly what I have in my last line of code.
Dim LastRow As Long
LastRow = Worksheets("Orders").Range("A" & Rows.Count).End(xlUp).Row
Worksheets("Orders").Range("A1:CU" & LastRow).AutoFilter Field:=10, Criteria1:="New"
If Worksheets("Orders").Range("A1:CU" & LastRow).SpecialCells(xlCellTypeVisible).Count > 1 Then
Worksheets("Orders").Range("A1:CU" & LastRow).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
Later in my code, I filter the same set of data again, this time deleting the non-visible (filtered out) rows. I am also getting the same error on the last line of this code as well:
Worksheets("Orders").Range("$A1:CC" & LastRow).AutoFilter Field:=26, Criteria1:= _
"=*Jazz*", Operator:=xlAnd
Dim oRow As Range, rng As Range
Dim myRows As Range
With Sheets("Orders")
Set myRows = Intersect(.Range("A:A").EntireRow, .UsedRange)
If myRows Is Nothing Then Exit Sub
End With
For Each oRow In myRows.Columns(1).Cells
If oRow.EntireRow.Hidden Then
If rng Is Nothing Then
Set rng = oRow
Else
Set rng = Union(rng, oRow)
End If
End If
Next
If Not rng Is Nothing Then rng.EntireRow.Delete
Any help on these errors would be much appreciated!
You dont need to invoke the SpecialCells before deleting, because the method Delete acts only on the visible rows. The problem might be due to this.
Besides, the test .SpecialCells(xlCellTypeVisible).Count > 1 is useless because the header row of the filtered range remains visible.
Here's a safer and simpler way to write your code:
With Worksheets("Orders").UsedRange
.AutoFilter 10, "New"
.Offset(1).EntireRow.Delete ' <--- no need for .SpecialCells
End With
Post by #A.S.H is a great illustration of minimalism, but your 1st code block is still fine.
Just to make a small correction, change .SpecialCells(xlCellTypeVisible).Count > 1 to .SpecialCells(xlCellTypeVisible).Count > 2 as pointed out by him. Also, don't forget to add the line Worksheets("Orders").ShowAllData at the end.
The 2nd code block is unnecessarily complicated (and hence likely error-prone). Instead, simply change the filter of the 1st code block to Criteria1:="<>New" if you want to eliminate other than "New" items.
The Run Time Error issue seems to be due to something else. Make sure the sheet is not protected.
To see if it's the code or the file format that's causing the problem, you can also test the same code on a new workbook copying just the data (paste value) from your existing one and then run the code.
You should remove any filters at the top of your code.
On Error Resume Next
If Worksheets("Orders").AutoFilter.FilterMode = True Then
Worksheets("Orders").ShowAllData
End If

VBA AutoFilter hiding all rows - including the ones matching criteria

I'm applying VBA AutoFilter to some results in an excel sheet. It seems to compile properly, but when I check the results, the AutoFilter is hiding both the rows that match and that do not match the criteria I applied.
If I manually select the autofilter that was applied, i see that the criteria that I coded is correctly input and, by just clicking enter, the criteria matching rows show.
I'm using a Brazilian Portuguese version of Excel, not sure if that might be the issue.
Here's what I've tried:
Sub FilterOff(ByVal thisSheet)
thisSheet.Activate
With thisSheet
.AutoFilterMode = False
.Range("A1:F1").AutoFilter
.Range("A1:F1").AutoFilter Field:=4, Criteria1:=">0.01", _
Operator:=xlOr, Criteria2:="<-0.01"
.Range("A1:F1").AutoFilter Field:=5, Criteria1:=">100"
End With
End Sub
I was experiencing something similar in one of my macros. I had a table that I was trying to autofilter. I could do it manually, but not in VBA, even when I was exactly replicating what the recording function gave me. I also could not copy+paste as values in VBA, but I could manually.
What worked for me was to save and close the workbook, then reopen it and apply the autofilter. Specifically, I used this:
tempWb.SaveAs ("dir\temp.xlsx")
tempWb.Close (0)
Set rptWb = Workbooks.Open("dir\temp.xlsx")
Set rptWs = rptWb.Sheets(1)
rptWs.Range(rptWs.Cells(1, 1), rptWs.Cells(lstRow, lstCol)).AutoFilter Field:=20, Criteria1:="=NO RECORD"
and it worked.
Update: I think the underlying issue was that I had calculation set to manual. After I set calculation to automatic, the problems went away.
I did something like this and it worked
Range("A1:B6").AutoFilter
ActiveSheet.Range("$A$1:$B$6").AutoFilter Field:=1, Criteria1:="=10", _
Operator:=xlOr, Criteria2:="=30"
ActiveSheet.Range("$A$1:$B$6").AutoFilter Field:=2, Criteria1:="100"

How can I autofilter when I'm not sure which column it will be?

I'm trying to automate the processing of various reports, which I just need to filter and count the rows of. I currently have a PowerShell script that opens each report and runs a few macros. It is just about in a working state, but I'd now like to make it a bit more intelligent and catch some of the fails, so I might be asking a few questions but I'll stick to the one problem on each.
The reports have similar, but not identical layouts. I am looking for a particular column name to then autofilter. I have a very basic and bodged together macro that currently does this, and works (most of the time) for example, sometimes the column I want is A or B:
If Worksheets(1).Range("A1") Like "*word" Then
Worksheets(1).Range("A1").AutoFilter Field:=1, Criteria1:="=criteria1", Operator:=xlOr, Criteria2:="=criteria2"
ElseIf Worksheets(1).Range("B1") Like "*word" Then
Worksheets(1).Range("A1").AutoFilter Field:=2, Criteria1:="=criteria", Operator:=xlOr, Criteria2:="=criteria2"
Hopefully that gives you the current picture.
I now want to instead, do a search for the field header I am looking for, then filter that column, so if the report format in future changes my macro won't break. Something similar to:
ColNum = Application.Match("*header", Range("A:Z"), 0)
ColNumInt = CInt(ColNum)
If ColNumInt > 0 Then
ActiveSheet.Range("A1").AutoFilter Field:=ColNumInt, Criteria1:="=criteria1*", Operator:=xlAnd
End If
But this gives an error "AutoFilter method of Range class failed", Googlefu says to turn off filters but they're already off. So I'm a bit stuck.
This part will always fail:
ColNum = Application.Match("*header", Range("A:Z"), 0)
since match only works on one row or column. So your code is actually returning Error 2042, which is then converted to 2042 by CInt. I guess you don't have that many columns of data, hence the autofilter fails. Use:
ColNum = Application.Match("*header", Range("A1:Z1"), 0)
If Not IsError(ColNum) Then
...
End If
This should work for you.
Sub Button1_Click()
Dim r As Range
Dim c As Integer
Set r = Range("A1:B1").Find(what:="*word*", lookat:=xlWhole)
c = r.Column
ActiveSheet.AutoFilterMode = 0
Columns(c).AutoFilter Field:=1, Criteria1:="*criteria1*"
End Sub

Excel error with intersect code

Good afternoon! I'm having another issue, and can't seem to figure it out. In this way too long filter macro, I have code that looks for the active cell within a range, and if it's there, performs a filter:
ElseIf Not (Intersect(ActiveCell, OpenFindingsRange)) Then
SourceFindings.Select
'Unfilter data
Application.Goto (Sheets("Source-Findings").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
ActiveSheet.ListObjects("tblFindings").Range.AutoFilter Field:=6, Criteria1:=FilterOperatingGroup
ActiveSheet.ListObjects("tblFindings").Range.AutoFilter Field:=36, Criteria1:=OpenStatus
ActiveSheet.ListObjects("tblFindings").Range.AutoFilter Field:=37, Criteria1:="Yes"
If the active cell isn't in that range, it should go to the next Else If statement, but that's not happening. I'm getting the following error: Object variable or With block variable not set.
I can't get around this, and for whatever reason, I can't get error handling to bypass it.
Thoughts?
Thx!
Intersect(), as you are using it, will return a Range and not a Boolean.