How to iterate over all the page breaks in an Excel 2003 worksheet via COM

Posted by Martin on Stack Overflow See other posts from Stack Overflow or by Martin
Published on 2008-09-16T22:41:20Z Indexed on 2010/04/18 2:13 UTC
Read the original article Hit count: 468

Filed under:
|
|
|

I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:

Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks();
long count = pHPageBreaks->Count;
for (long i=0; i < count; ++i)
{
  Excel::HPageBreakPtr pHPageBreak = pHPageBreaks->GetItem(i+1); 
  Excel::RangePtr pLocation = pHPageBreak->GetLocation();

  printf("Page break at row %d\n", pLocation->Row);

  pLocation.Release();
  pHPageBreak.Release();
}
pHPageBreaks.Release();

I expect this to print out the row numbers of each of the horizontal page breaks in pSheet. The problem I'm having is that although count correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling pHPageBreaks->GetItem(i) throws an exception, with error number 0x8002000b, "invalid index".

Attempting to use pHPageBreaks->Get_NewEnum() to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to Get_NewEnum().

I've looked around for a solution, and the closest thing I've found so far is http://support.microsoft.com/kb/210663/en-us. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help.

If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome!

Thank you.

@Joel: Yes, I have tried displaying the user interface, and then setting ScreenUpdating to true - it produced the same results. Also, I have since tried combinations of setting pSheet->PrintArea to the entire worksheet and/or calling pSheet->ResetAllPageBreaks() before my call to get the HPageBreaks collection, which didn't help either.

@Joel: I've used pSheet->UsedRange to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.

© Stack Overflow or respective owner

Related posts about c++

Related posts about excel