In my Excel spreadsheet I have two columns.
- A contains strings with the values 'Yes', 'No' or 'Maybe'.
- B contains strings with a year in.
I need a function to determine the number of occurrences of a year in column B, where the equivalent value in column A is 'Yes'.
I currently have the following code:
Function CountIfYearAndValue(Rng As Range, YNM As String, Year As String) As Integer
Dim count As Integer
count = 0
For Each c In Rng.Cells
If (StrComp(Abs(c.Value), Year, vbTextCompare) = 0) And (StrComp(Cells(c.Row, A), YMN, vbTextCompare) = 0) Then count = count + 1
Next
CountIfYearAndValue = count
End Function
The idea of this code is that we iterate through every cell in the range given (a range on column B) and check if the year is equal to the Year parameter. And if the equivalent cell on column A is equal to the YNM parameter we increment the count variable.
For some reason this code does not work when I use the following parameter:
=CountIfYearAndValue('Years'!B1:B7,"Yes","Year 7")
It just does the #VALUE error and refuses to display any outcome.
Any help would be much appreciated.
Edit: All of the values in both cells are on of an unformatted datatype ('General') and no cells are blank.
Cells(c.Row, A). You should add quotes toA:Cells(c.Row, "A")and 2) in functions parameters you are usingYNM As String, but in code you are usingStrComp(Cells(c.Row, A), YMN, vbTextCompare). Note, there isYMNandYNM. I suggest you to useOption Explicitto avoid such kind of errorsCOUNTIFfunction, but I'm interested to see why it still doesn't work. I implemented your changes and it still doesn't work with the same#VALUEerror.