Hello,
I’m trying to write a user-defined function that can iterate through cells in a range and do some operation based on the text in the cells. For example, I’d like a CountText function that I could invoke in the workbook as a cell formula (something like =CountText(A1:B2)
), and it would return the number of cells in A1:B2 whose text was the word “Text”. This is what I’ve come up with so far:
Function CountText(range)
Dim result As Integer
result = 0
For col = 0 To range.Columns.getCount() - 1
For row = 0 To range.Rows.getCount() - 1
Dim cell
cell = range.getCellByPosition(col, row)
If StrComp(cell.String, "Text") = 0 Then
result = result + 1
End If
Next
Next
CountText = result
End Function
When I invoke this in a cell formula =CountText(A1:B2)
I get this error:
“BASIC runtime error. Object variable not set.”
The message highlights the line with the first For loop. I wrote these loops based on the answer in this post (cycle through Cells in a Range). What am I missing here?
I see that this method of iterating over column and row counts only works for rectangular ranges, but what happens if range is a union (something like =CountText(A1:B2~C3:D4)
)? Is there some way to use a For Each loop for this?
I also get a different error if I try to invoke it with just one cell in the range (=CountText(A1)
). Is it not legal to have a range object with only one cell?
I’d really appreciate some pointers in the right direction with this.
Thank you!