I have this piece of code getting a "No Cells Found" error. I don't understand why if I am using on error resume next and there will be times there won't be any "INATIVE" in that column.
Intersect(.UsedRange, .UsedRange.Offset(1)).SpecialCells(12).EntireRow.Delete
where 12 can also be written as xlCellTypeVisible.
Here are the lines before and after for more clarity:
With Sheets("Temp Activos")
On Error Resume Next
.UsedRange.AutoFilter 6, "INATIVE"
On Error GoTo 0
Intersect(.UsedRange, .UsedRange.Offset(1)).SpecialCells(12).EntireRow.Delete
r = WorksheetFunction.CountA(.Range("A:A"))
.UsedRange.AutoFilter
Converting comment to answer:
The On Error GoTo 0 clears the On Error Resume Next condition. So you'll need to move the On Error GoTo 0 down until just before the End With.
Related
I have an issue with the error handling in VBA.
The code has previously worked, but now suddenly errors are not handled by On Error GoTo statements and instead the code is crashing and giving a pop up with the error message as if On Error GoTo 0 would be active.
Here is an example of how the code structure is:
On Error GoTo logError
For d = 0 To Doclist.Count -1
On Error GoTo DownloadFailed
session.findById("wnd[0]/tbar[1]/btn[30]").press
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
On Error GoTo logError
...
DownloadFailed:
Err.Clear
On Error GoTo logError
Next d
logError:
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save
In the first iteration the On Error GoTo DownloadFailed is working as expected, but after this the code is crashing.
The error that I am getting is Run-time error '619'.
I saw on some similar post to clear the error with Err.Clear but this did nothing to my code.
In another part of the code I am using On Error Resume Next which at the same time stopped working.
As mentioned the code has worked previously so I have no idea what could be wrong.
Does anybody have experience with similar issues and any possible solutions for this?
Error Handling
The GoTo keyword is kind of reserved for the error-handling routine so this solution is strict about that.
Some contributors argue though that it is OK to use the GoTo keyword to skip a code block in a loop but I don't think it refers to doing it with On Error.
Sub ErrorTest()
Dim LogErrorFound As Boolean
Dim ErrNum As Long
On Error GoTo LogError ' start error-handling routine
For d = 0 To Doclist.Count - 1
On Error Resume Next ' defer error trapping
session.findById("wnd[0]/tbar[1]/btn[30]").press
ErrNum = Err.Number
If ErrNum = 0 Then
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
ErrNum = Err.Number
End If
On Error GoTo LogError ' resume error-handling routine; clears error
If ErrNum = 0 Then
'...
'Else ' download failed i.e. 'ErrNum <> 0'; do nothing!?
End If
Next d
ProcExit:
If LogErrorFound Then
On Error Resume Next ' defer error trapping; avoid endless loop
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save
On Error GoTo 0 ' stop error trapping
MsgBox "A log error occurred.", vbCritical
Else
MsgBox "Finished successfully.", vbInformation
End If
Exit Sub
LogError: ' continuation of the error-handling routine
LogErrorFound = True
Resume ProcExit
End Sub
While Err.Clear does clear the error object, it does not re-enable error handling like Resume or On Error GoTo 0. In order to manually do this, replace Err.Clear with On Error GoTo -1 like this:
On Error GoTo logError
For d = 0 To Doclist.Count -1
On Error GoTo DownloadFailed
session.findById("wnd[0]/tbar[1]/btn[30]").press
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
On Error GoTo logError
...
DownloadFailed:
On Error GoTo -1
On Error GoTo logError
Next d
logError:
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save
I currently have this, but I dont necessarily need a loop. I just need to see if there is any error in the usedrange, and if yes, stop the code and display the message. If no error, then just continue with the rest of the steps that are after this part of the code. Right now this loop displays this message for every error detected. I just need it to be displayed once if any error is found, and then stop the code.
Dim r As Range
For Each r In ws_DST.UsedRange
If IsError(r.Value) Then
MsgBox "Please fix any errors", vbOKOnly
End If
Next
End
How about:
Sub errortest()
On Error Resume Next
Set Rng = Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If Rng Is Nothing Then
Exit Sub
Else
For Each r In Rng
MsgBox r.Address(0, 0)
Next r
End If
End Sub
My macro generates yahoo ticker download URL's for specific companies. I generate 3 URL's per ticker, each having a different date segment for the data download.
The problem that I have, is that data does not exist for some of the dates, hence an error is returned from Yahoo which causes my Macro to crash.
I've attempted the following with a GOTO label:-
On Error GoTo error_handler
Workbooks.Open Filename:=("http://chart.finance.yahoo.com/table.csv?s=FAN.L&a=2&b=04&c=2014&d=2&e=21&f=2014&g=d&ignore=.csv")
however this does not work, it does not GOTO the label.
Any ideas would be greatly appreciated.
Try this:
On Error Resume Next
Workbooks.Open Filename:=("http://chart.finance.yahoo.com/table.csv?s=FAN.L&a=2&b=04&c=2014&d=2&e=21&f=2014&g=d&ignore=.csv")
On Error GoTo error_handler
The On Error Resume Next will allow it to the skip ahead.
Download the file with seperate error handling and then if-check
If Dir(MyFileName) <> "" Then
Workbooks.Open Filename:="C:\123.xls"
Else
MsgBox "Spreadsheet could not be found in C:\", vbCritical + vbOKOnly, "File not found"
End If
Here is some example of error handling. Replace your code with the Debug.print 5/0 and it should work.
Public Sub ErrorHandlingExample()
On Error GoTo ErrorHandlingExample_Error
Debug.Print 5 / 0
On Error GoTo 0
Debug.Print "No error"
Exit Sub
ErrorHandlingExample_Error:
Debug.Print "Error was found - " & Err.Description
End Sub
I am running a bit of VBA to switch an entire Excel worksheet to upper case.
However it trips over and gives a Type Mismatch error and fails half way through.
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
If Len(cell) > 0 Then cell = UCase(cell)
Next cell
Application.ScreenUpdating = True
End Sub
I'm assuming it is tripping over a specific cell however there are hundreds of lines. Is there a way to get it to skip errors
If you want to convert all cells to upper case text (including formulas):
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range, v As String
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
v = cell.Text
If Len(v) > 0 Then cell.Value = UCase(v)
Next cell
Application.ScreenUpdating = True
End Sub
Be aware that all formulas not returning Null will also be converted to Text.
To see what cell (or cells) is the problem, you could try:
On Error Resume Next 'to enable in-line error-catching
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
If Len(cell) > 0 Then cell = UCase(cell)
If Err.Number > 0 Then
Debug.Print cell.Address
Err.Clear
End If
Next cell
On Error GoTo 0 'Turn off On Error Resume Next
On Error Resume Next is often abused, especially by new VBA programmers. Don't turn it on at the beginning of a sub and never turn it off and never check Err.Number. I find it a very good idea to think of it having a specific scope, and emphasizing that scope by indenting the statements in it, as I have done above. #MacroMan raises a good point that errors shouldn't be simply ignored (which is what happens if you abuse this construct).
Add the following error trapping in the middle of your code:
On Error Resume Next
If Len(cell) > 0 Then cell = UCase(cell)
If Err.Number <> 0 Then
MsgBox "Cell " & cell.Address & " has an error !"
End If
On Error GoTo 0
Note: Your code is fine with Numeric values, it's the #NA and #DIV/0 that's raising the errors when running your original code.
I have the following code:
ErrNr = 0
For Rw = StRw To LsRw 'ToDo speed up with fromrow torow
If Len(ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl)) = 0 Then
ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl).Interior.ColorIndex = 46
ErrNr = ErrNr + 1
End If
Next
My problem is if there is an error on the page, my code is not running after that. I think the solution should be with:
On Error Resume Next
N = 1 / 0 ' cause an error
If Err.Number <> 0 Then
N = 1
End If
But I don't know how to use this code.
It depends on what you want to do.
On Error Resume Next will ignore the fact that the error occurred. This is a great way to get your code to execute to completion, but will just about guarantee that it won't do what you want.
On Error Goto 0 is the default response. It will pop up the error message that VBA is generating
On Error Goto <label> will cause your code to jump to a specified label when an error occurs and allows you to take an appropriate action based on the error code.
The last option, On Error Goto <label> is usually the most useful, and you'll want to do some digging on how to best use it for your application.
This site is where I got the details above from, and is usually the first results that comes from Googling for "excel vba on error". I've used that reference myself a number of times.
I have interpreted your requirement as to how to handle common worksheet errors when looping through a range of cells and examining the values. If you attempt to look at a cell that contains an error (e.g. #N/A, #DIV/0!, #VALUE!, etc) you will get something like:
Runtime error '13':
Type mismatch.
These can be caught with VBA's IsError function.
Dim rw As Long
With ThisWorkbook.Sheets(TsSh)
For rw = StRw To LsRw
If IsError(.Cells(rw, 1)) Then
.Cells(rw, 1).Interior.ColorIndex = 10
ElseIf Not CBool(Len(.Cells(rw, 1).Value2)) Then
.Cells(rw, 1).Interior.ColorIndex = 46
End If
Next rw
End With
In the above, I am catching the cells with an error and coloring them green. Note that I am examining them for errors before I check for a zero length.
I generally try to avoid On Error Resume Next as it will try to continue no matter what the error (there are some cases where it's useful though).
The code below passes all errors out of the procedure where they can be handled on a case by case basis.
Sub test1()
Dim n As Double
On Error GoTo ERROR_HANDLER
n = 1 / 0 ' cause an error
On Error GoTo 0
Exit Sub
ERROR_HANDLER:
Select Case Err.Number
Case 11 'Division by zero
n = 1
Err.Clear
Resume Next
Case 13 'Type mismatch
Case Else
'Unhandled errors.
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure test1."
Err.Clear
End Select
End Sub