Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect merged cells in VBA Excel with MergeArea

Tags:

merge

excel

vba

I'm having quite an issue with this one - I have to detect horizontally and vertically merged cells from an excel table. I have to store the first cell coords, and the lenght of the merged area. I iterate through the table with two for-cycles, line by line.

How can I use MergeArea property to detect the merged and non-merged areas? If the cell is not merged, it should probably return empty range, however, this:

"If currentRange Is Nothing Then"

is not working at all. Any ideas? Thanks a lot.

like image 237
zirael Avatar asked Feb 27 '14 17:02

zirael


People also ask

Does VBA work with merged cells?

In VBA, there is a “MERGE” method that you can use to merge a range of cells or even multiple ranges into one. This method has an argument “Across” which is optional. If you specify TRUE it will merge each row in the range separately, and if you specify FALSE it will merge the entire range as one.

How do you check if a cell is merged?

Method 1: Use Find Feature Now in the “Find Format” window, choose the tab “Alignment”. And then check the option “Merge cells” in the “Text control” part. After that, click the button “OK” in the window. Now you will come back to the “Find and Replace” window.


2 Answers

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells  True 

How many cells are merged?

? Activecell.MergeArea.Cells.Count  2 

How many columns are merged?

? Activecell.MergeArea.Columns.Count  2 

How many rows are merged?

? Activecell.MergeArea.Rows.Count   1 

What's the merged range address?

? activecell.MergeArea.Address   $F$2:$F$3 
like image 107
tbur Avatar answered Sep 20 '22 08:09

tbur


While working with selected cells as shown by @tbur can be useful, it's also not the only option available.

You can use Range() like so:

If Worksheets("Sheet1").Range("A1").MergeCells Then   Do something Else   Do something else End If 

Or:

If Worksheets("Sheet1").Range("A1:C1").MergeCells Then   Do something Else   Do something else End If 

Alternately, you can use Cells():

If Worksheets("Sheet1").Cells(1, 1).MergeCells Then   Do something Else   Do something else End If 
like image 34
David Metcalfe Avatar answered Sep 21 '22 08:09

David Metcalfe