PDA

View Full Version : Untrapped Error 9 in code



IanFScott
11-10-2011, 07:21 AM
Does anyone else find that updating a sheet using vba causes error 9 (Subscript of of range) to occur but the code itself is NOT interupted.

With RegSheet
With .Range(.Cells(4, 1), .Cells(NumRecs + 4, 8))
Err.Clear
.Value = arrayReg ' Error 9 thrown here
.Borders.LineStyle = xlContinuous ' But not here
.Borders.Weight = xlThin ' Or here
End With
Err.Clear
.Range("B6").Value = 2 ' Error 9 thrown here
Err.Clear
.Range("B6").Value = "Text" ' And here
Err.Clear
.Range("B6").Formula = "=SUM(C6:F6)" ' And here
Err.Clear
RegSheet.Rows("4:2000").Delete ' and here
End With

Stepping through the above code (Regsheet and arrayReg etc. are set earlier) the error shows up (using the watch window) on each occasion the sheet is changed.
The work around is to use Application.EnableEvents = False even if, as in this case, there is no code using events.
The workbook was originally a 2003 .xls and is now saved as a 2007 .xslm

Kenneth Hobs
11-10-2011, 06:33 PM
You posted partial code. Your first line of code should be Option Explicit. We don't know what NumRecs resolves to for example.

Aflatoon
11-11-2011, 06:03 AM
We also do not know why that code is being called each time the sheet changes if there are no change events - are you sure there is not a workbook- or application-level sheetChange event?

IanFScott
11-14-2011, 01:48 AM
Sorry, I probably did not make clear - it is only a fragment of code to indicate the type of statements which cause the untrapped error to show.
The code is from a system developed in Excel 2003 and runs correctly there. I have also established since posting that there is no problem in Office 2010.
The code itself runs correctly in Office 2007 (that is to say code is NOT halted when the error is thrown up) but if, as I do at times, you turn error checking off (On Error Resume Next) and then use you own system to trap errors then you get false positives.
e.g. just after executing one of the type of untrapped error causing statements you have:
Set WB = Workbooks.Open(FPath & FName)
If Err.Number <> 0 Then
MsgBox "FName not available"
.... etc. etc.

Even if the workbook opens OK, as Err.Number is already 9 the failure code runs.
I guess what I am trying to establish is whether it is something unique to our Office 2007 set up here or whether this is a 'Fault/Bug' known in Office 2007.

Aflatoon
11-14-2011, 01:59 AM
I am not aware of any differences in error handling between 2007 and other versions.