I had an issue yesterday with my previous Excel VBA project where the user is experiencing the very common:
Run-time error '9':
Subscript out of range
Surprisingly, i found out that the said exception was being raised on a foreach construct for the pagebreak collection specifically when it hit the following line:
For Each verticalPageBreak In aWorksheet.VPageBreaks
columnIndex = verticalPageBreak.Location.Column
....
Next
I was scratching my head, why the hell would a foreach construct raise a subscript out of range exception! As usual, i did a research on usenet, because for scenarios like this, i'm sure there's another guy who had previously bumped into the said issue, i found one here.
Turns out that the pagebreaks collection in Excel is buggy. This was illustrated by a known bug in excel found in this Knowledge Base. I tried doing the hacks proposed by the guys in the usenet post to no avail (and besides, i do not understand those SendKeys and the Excel4ForMacro workarounds).
My requirement was just to redefine valid vertical pagebreaks because i will be printing a long landscaped worksheet. What's weird is I also found out that the said exception is existing if i have a smaller screen resolution (1024x768 and below), however it is not encountered on computeres having a bigger resolution, this means cause #2 from the KB is the root of the problem.
However, selecting the rightmost used cell as suggested by the KB did not solve the problem. Luckily i found my own hack by having the ActiveWindow ScrollColumn set to be the last used column before doing the vertical page break iteration. Issue closed.
Posted
05-08-2007 3:45 PM
by
jokiz