I always receive type missmatch errors or division by zero errors while trying to implement following: I just want to count the number of unique entries in a range, the entries in the range are of “class” text:
startRow = 3
startColumn = 1
col = "A"
Set topCell = Cells(startRow, startColumn)
Set bottomCell = Cells(Rows.Count, startColumn)
If IsEmpty(bottomCell) Then Set bottomCell = bottomCell.End(xlUp)
Set selectRows = Range(col & topCell.Row & ":" & col & bottomCell.Row)
nRows = WorksheetFunction.CountA(selectRows)
test = WorksheetFunction.SumProduct(WorksheetFunction.IsText(selectRows) / WorksheetFunction.CountIf(selectRows, selectRows))
I have a bug in the computation for test, but I don’t get it. Some help very appreciated
Thanks a lot
BR
Martin
Your first problem is the
WorksheetFunction.CountIf(selectRows, selectRows)part of yourtestcalculation. When there are no duplicates, this will result in a division by zero error. This will occur when typed into a worksheet as well, so you will either need to change your logic, or test for this case first.Your
Type Mismatchproblem, I believe, is caused by theWorksheetFunction.IsText(selectRows)segment. I have not been able to figure out what is causing it, but as i mentioned in my comments, I think theIsText()function may not take a range in VBA like it does when typed into a cell.I would probably approach this problem in a different way. Here’s an example I found elsewhere on SO Count unique values in Excel
This mostly has worksheet formulas, but there is 1 answer with VBA code that you probably could adapt.
Another option is to create a collection and count the number of elements