We help IT Professionals succeed at work.
Get Started

Count range cells eliminating merge cells

Last Modified: 2013-11-10
I have created a method to count the number of cells in a range taking into consideration that merged cell are counted as one cell.

Here is the method

private static int getRangeCount(Range Target)
      if (Target == null)
            return 0;
      if (Target.Cells == null)
            return 0;
      if (Target.Cells.Count <= 1)
            return Target.Cells.Count;
      int count = 0;
      foreach (Range cell in Target)
            if (cell.MergeCells != null && cell.MergeCells is bool && (bool)cell.MergeCells)
                  Range rng = (Range)cell.MergeArea[1, 1];
                  if (!Microsoft.Office.Tools.Excel.ExcelLocale1033Proxy.ReferenceEquals(cell, rng))
                        string str1 = WorkbookUtils.GetAddress(cell, XlReferenceStyle.xlA1);
                        string str2 = WorkbookUtils.GetAddress(rng, XlReferenceStyle.xlA1);
                        if (str1 == str2)
      return count;
My problem now is that a user is using this method on a range with 8448 cells. Because the target is so big the method takes a very very very long time.

Is there a way to improve the above code?

Watch Question
Top Expert 2011
This problem has been solved!
Unlock 2 Answers and 26 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE