VBA stops running after filtering data, but with no error message - vba

I am trying to filter data using the advanced filter, and then copy the visible cells to a separate sheet in the workbook:
Dim S_ALR, OUTPUTS, INPUTS As Worksheet
Set S_ALR = ActiveWorkbook.Sheets("S_ALR_87012357")
Set OUTPUTS = ActiveWorkbook.Worksheets("OUTPUTS")
'clear data
Worksheets("OUTPUTS").Range("A:AK").ClearContents
'copy Outputs from S_ALR_87012357 to OUTPUTS tab
S_ALR.Range("A:AK").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _
Sheets("FILTERS").Range("A3:B9"), Unique:=False
S_ALR.Range("A:AK").SpecialCells(xlCellTypeVisible).Copy
OUTPUTS.Cells(1, 1).PasteSpecial
However, after the data is filtered the macro stops with no error message.
I have commented out the filter and ran the macro & the rest of the code works properly. I have also tried incorporating the copy/past into the filter itself by putting CopyToRange in the filter, but that also hasn't worked.
I'm quite new to this, so it may be something simple that I am missing, but I'm absolutely stumped!
Please help.

Old question but thought I'd add an answer as I've just had the same issue and spent an hour looking into it. Turns out the fix seems to just be restarting Excel (closing down all Excel windows and reopening), and the AdvancedFilter line executed without issue for me after that.
For reference my line of code that exhibited the same behaviour was:
Range("B1:B1808").AdvancedFilter Action:=xlFilterInPlace, Unique:=True
In response to the original question's comments:
Yes the code just stops, I stepped through my code, got to the Advanced Filter line, the AdvancedFilter line is then executed but the next line doesn't get stepped into, it's as if the AdvancedFilter line acted like an 'End' command
The AdvancedFilter line's execution succeeded, VBA just didn't continue onto the next line for some reason. I put a debug.print line after and it was never exectuted.
No Worksheet_Calculate event was being triggered, the workbook I was doing my testing in only had that single AdvancedFilter line of code (within a 'sub test' - 'end sub' of course)
While testing I explicitly added an 'On Error GoTo 0' before the AdvancedFilter line and this had no effect

Related

Run-Time Error '1004' in VBA Subroutine

There seems to be something wrong with one of my Excel Objects. Take a look at the below snippet. I created the subroutine Run_all(), and when I step through, it'll go up to the Function row_count() and start executing, however, when it gets to the first highlighted row, I get the error.
**The Sheet that I'm referencing in the function is typed correctly. For example, if I run the bottom subroutine CA_Copy_Paste_, it works correctly and I get no errors.
Why is Excel not recognizing "Sheet 3" in the function? For more context, it only works if I type "Sheet4". Does not work on "Sheet1" or "Sheet2" either.
If you insist on using .Select and .Activate to accomplish your goals then you must activate the worksheet before activating or selecting a cell or range of cells on that worksheet.
worksheets("sheet 3").activate
activesheet.range("c4").activate
If you wish to use some 'shorthand' to try and accomplish this in a single line of code then switch to the Application.GoTo method.
Application.Goto reference:=worksheets("sheet 3").range("c4")
In any event, you are best off avoiding the use of select and activate. See
How to avoid using Select in Excel VBA.

Attempt to reference a sheet yields "Run Time Error 1004"

I'm just trying to select a column so that I can change the date format. I have no idea why, but my code is giving me a huge issue anytime I try to reference the sheet the column is in. But what I don't understand is that many times earlier in my code I successfully reference the sheet with no issues.
Has anyone seen this?
Did VBA just forget about me defining and setting my variable?
Here's an example of my code:
Dim wbPrescrub As Workbook, wsPrescrub As Worksheet
Set wbPrescrub = ThisWorkbook
Set wsPrescrub = wbPrescrub.Sheets("PreScrub")
wsPrescrub.Range("A1").AutoFilter Field:=5, Criteria1:=(""), _
Operator:=xlFilterValues
wsPrescrub.Range("E2:E" & pslastRow).SpecialCells (xlCellTypeBlanks).EntireRow.Delete
wsPrescrub.AutoFilterMode = False
wsPrescrub.Columns("F:F").EntireColumn.AutoFit
wsPrescrub.Columns("F:F").Select
Selection.NumberFormat = "mm/dd/yyyy"
I included lines of my code which worked fine, it is the last two lines that are giving me trouble. I cannot get past the wsPrescrub.Columns line. If I run the code without referencing the sheet it works perfectly fine on the ActiveSheet and correctly selects the column and format. But the second I add in what sheet to look at I get:
Run Time Error 1004: Application-defined or object defined error

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

Run-time error '-2147188160(80048240) DataType:=ppPasteEnhancedMetafile Error

Seems there is some bug. Can't resolve this problem, all code is running fine and I am able to see the AutoShape is getting copied from Excel file but it is not adding it to PowerPoint. Popping up an error Run-time error '-2147188160(80048240) View.Pastespecial : Invalid Request. The specified data type is unavailable
If Range("H" & i).Value = 1 And Range("B" & i).Value = "FRONT" Then
objPPT.Presentations(1).Slides(9).Select
objPPT.ActiveWindow.View.PasteSpecial DataType:=ppPasteEnhancedMetafile
Your code will be faster and possibly more reliable if you don't rely on selecting anything:
With objPPT.Slides(9).Shapes
Set objShape = .PasteSpecial(ppPasteEnhancedMetafile)(1)
With objShape
' set coordinates and such here
End With
End With
As to why you're getting the error message, try stopping the code after you've put something on the clipbard. Then switch to PowerPoint, use Paste Special to see what paste options are available. If EMF isn't one of them, that's your problem ... you're not putting anything in EMF format on the clipboard.
I had a similar issue, but I found a different solution; it may be specific to what I was doing though.
I setup a program where I would:
(manual) Copy an entire webpage that was a report on several performance metrics
(manual) Pasted it in to excel
Run the program to extract the values I want and then clear contents of the sheet I pasted them on.
Eventually after many tests, it would fail with this same automation error when I tried to access the sheet:
Sheets("PDX Paste").Activate
I was able to activate every other sheet except that particular one, even using the index value instead of the direct name reference. After googling to no success I found out that the copy and paste from the website was also pasting invisible controls. When I found this out I had 1,300+ shapes when I only expected 1 (the button I use to trigger the program). It was actually only apparent when a glitch - presumably due to so much memory being used to store these controls - displayed for a few seconds.
I ran the following code independently and then appended it to the end of my program when I do the cleanup of the data. The code goes through the sheet and deletes any shape that isn't the same type as my button. It would have to be adapted if the shapes you want to delete are the same type as the shapes you want to keep. It also becomes simpler if you don't have any shapes to keep.
Dim wsh As Worksheet
Set wsh = ActiveSheet
Dim i As Integer
For i = wsh.Shapes.Count To 1 Step -1
If wsh.Shapes(i).Type <> wsh.Shapes("UpdateDataButton").Type Then
wsh.Shapes(i).Delete
End If
Next i
I'm not sure this would solve this problem, but hopefully this can help others and prevent loss of time figuring out what may be causing this relatively vague error message.