Excel error with intersect code - vba

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.

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

Skip code when filters applied and returns no results 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

Excel 2013 VBA clear active filter

I need to clear any active filters from a sheet before running a certain macro, this line works just fine IF there is an active filter on
If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData
However if no filters are selected it returns the error
Runtime error '1004';
ShowAllData method of Worksheet class failed
I got that code from an answer to this question
Excel 2013 VBA Clear All Filters macro
However that question doesn't explain how to ignore the line if no filters are active.
How do I ignore this line if there are no currently active filters applied?
EDIT
For example, all column headings have been auto filtered, so if my sheet is filtered by 'Female' for example I need to remove that filter before running the macro, however if no filters have been applied, just run the macro as normal
Use FilterMode instead of AutoFilterMode. I have dealt with filters frequently and this code works fine.
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
Make sure the worksheet is not protected as this also gives the 1004 error.
I sincerely admire your desire to program for specific circumstances but I have to admit that the quickest way to accomplish this is with On Error Resume Next.
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0
You shouldn't have to break something to check if it exists but in VBA that is occasionally the best recourse. Personally, I rank On Error Resume Next right up there with SendKeys as a programming method.
The above method does not require that you check to see if .AutoFilterMode is True.
I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..
Hopefully this helps someone out there :)
Sub ResetFilters()
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
Next 'Check next worksheet in the workbook
Next
End Sub
** Possible duplicate of thread: Excel 2013 VBA Clear All Filters Macro

Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class

In my macro, I have the following code :
i = Application.WorksheetFunction.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)
where 'str_accrual' is a string captured earlier to this line and the Range selected is in a single row say from "A1" to "BH1" and the result will be a number which is the position of that string in that range selected.
When I run the macro, I get the error:
Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class
But when I run the macro line by line using (F8) key, I don't get this error but when I run the macro continuously I get the error. Again, if the abort the macro and run it again the error doesn't appear.
I tried several times. It seems that if there is no match, the expression will prompt this error
if you want to catch the error, use Application.Match instead
Then you can wrap it with isError
tons of posts on this error but no solution as far as I read the posts. It seems that for various worksheet functions to work, the worksheet must be active/visible. (That's at least my latest finding after my Match() was working randomly for spurious reasons.)
I hoped the mystery was solved, though activating worksheets for this kind of lookup action was a pain and costs a few CPU cycles.
So I played around with syntax variations and it turned out that the code started to work after I removed the underscore line breaks, regardless of the worksheet being displayed. <- well, for some reason I still had to activate the worksheet :-(
'does not work
'Set oCllHeader = ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, _
Application.Match( _
strValue, _
ActiveWorkbook.Worksheets("Auswertung").Range( _
oCllSpielID, _
ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, lastUsedCellInRow(oCllSpielID).Column)), _
0))
'does work (removed the line breaks with underscore for readibility) <- this syntax stopped working later, no way around activating the worksheet :-(
Set oCllHeader = ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, Application.Match(strValue, ActiveWorkbook.Worksheets("Auswertung").Range(oCllSpielID, ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, lastUsedCellInRow(oCllSpielID).Column)), 0))
In the end I am fretting running into more realizations of this mystery and spending lots of time again.
cheers
I was getting this error intermittently. Turns out, it happened when I had a different worksheet active.
As the docs for Range say,
When it's used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet.
So, to fix the error you add a qualifier:
Sheet1.Range
I had this issue using a third-party generated xls file that the program was pulling from. When I changed the export from the third-party program to xls (data only) it resolved my issue. So for some of you, maybe there is an issue with pulling data from a cell that isn't just a clean value.
I apologize if my nomenclature isn't great, just a novice to this.
That is what you get if MATCH fails to find the value.
Try this instead:
If Not IsError(Application.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)) Then
i = Application.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)
Else
'do something if no match is found
End If
Update
Here is better code that does not rely on Selection except as a means of user-input for defining the range to be searched.
Sub Test()
Dim str_accrual As String
Dim rngToSearch As Range
str_accrual = InputBox("Search for?")
Set rngToSearch = Range(Selection, Selection.End(xlToRight))
If Not IsError(Application.Match(str_accrual, rngToSearch, 0)) Then
i = Application.Match(str_accrual, rngToSearch, 0)
MsgBox i
Else
MsgBox "no match is found in range(" & rngToSearch.Address & ")."
End If
End Sub
I used "If Not IsError" and the error kept showing. To prevent the error, add the following line as well:
On Local Error Resume Next
when nothing is found, Match returns data type Error, which is different from a number. You may want to try this.
dim result variant
result = Application.Match(....)
if Iserror(result)
then not found
else do your normal thing

VBA Concatenating columns from same worksheet in Range

I am having trouble concatenating two columns (variable range) to another column in the same document. Is there something really obvious I'm missing?
Function ConcCol(ConVal_1 As String, ConVal_2 As String)
Range("V30:V500").Select
Application.CutCopyMode = False
With ActiveCell
.FormulaR1C1 = "=CONCATENATE(RC[5],"" "",RC[6])"
End With
Selection.AutoFill Destination:=Range(Destination), Type:=xlFillDefault
End Function
When running the above function, I get the following error:
Error: Run-time error '1004': AutoFill method of Range class failed
I assume it's something to do with only one cell being activated perhaps? My VBA knowledge is limited
Sub ConcCol()
Range("V3:V500").Select
For Each Cell In Selection
Cell.Value = "=CONCATENATE(RC[5],"" "",RC[6])"
Next Cell
End Sub
I think it'd be easier (if you're going with the selection idea), to just use each cell. I think your with statement doesn't want to loop at all, hence error. This works, a simple solution.
I think this is what you're looking for:
Sub tgr()
With Intersect(ActiveSheet.UsedRange.EntireRow, Range("V30:V" & Rows.Count))
.Formula = "=AA" & .Row & "&"" ""&AB" & .Row
End With
End Sub
Hey I think you are a bit confused. How do you plan to run this code? You need to provide more details. Here are three ways of running a vba code:
User Interface as a User Defined Function (UDF)
As a Function that is called/used by another VBA code
AS a macro and user need to run it from the macro list
For your purpose, why doesn't the user use CONCATENANTE function in the sheet and fill down?
Maybe use the Excel array functions?
I cannot post images, need 10 reputations :s