Wednesday, 27 January 2010

Excel VBA macros fail with merged cells

If you use a VBA macro to read or set the contents of a merged cell in Excel it appears to fail. The code I used for a non-merged cell was

    appExcel.ActiveSheet.Range("A35").select
    sContent = appExcel.Selection.Text

Reading the value for a merged cell returns a null pointer for each of the cells that are merged, where you might expect the top left cell at least to return the value Excel shows if you click in the merged cell. The code below reads the value correctly:

    Set objRange = appExcel.ActiveSheet.Range("A35").MergeArea
    sContent = objRange.Cells(1, 1)

Thanks to Antonio Bayah for the initial tip that led me to this.

No comments: