2

I am trying to count the number of rows where a specific string appears in column K in a worksheet using a loop. The strings used for the search reside in Scorecards B2:B8. The count should be placed in the next column, C in this case. I am trying to pass the string in "op_id" to countif. When I run it all counted values in column C are 0. Here is what I have so far:

Dim op_id As String For i = 2 To 8 op_id = Sheets("Scorecards").Cells(i, 2) Sheets("Scorecards").Cells(i, 3) = "=COUNTIF('Raw Data'!K:K, & op_id)" Next i 

Thanks in advance!

1
  • Can you specify which version of Excel you are using? Commented Feb 26, 2013 at 8:17

2 Answers 2

2

Unless your example is oversimplified, there is no need to use VBA here since you can use SUMPRODUCT to the same effect, e.g.:

=SUMPRODUCT(1*('Raw Data'!K:K=B2)) 

...and drag down to apply to as many rows as you need.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'll keep this in my tool bag. I'm using vb because the folks I support are doing many manual calculations and I'm trying to make it a easy for them as possible.
1

The problem is that VBA does not support string interpolation. You need to concatenate instead:

Dim op_id As String For i = 2 To 8 op_id = Sheets("Scorecards").Cells(i, 2) Sheets("Scorecards").Cells(i, 3) = _ "=COUNTIF('Raw Data'!K:K, """ & op_id & """)" Next i 

4 Comments

Didn't know that being a noob. Thanks! Exactly what I wanted.
As a follow-up: Can I somehow nest this or use it when I have multiple criteria? Example: Using the strings (b2:b8) above as well as a couple other columns on the Raw Data sheet. Process: 1. Count the rows with strings above (more info: they are user ids). 2. Count rows containing Fail for strings Pass, Fail for each user id. 3. count rows for critical fail for each fail for each user. Hopefully that makes sense
@user2108935 I don't know how that would be done using a formula, unless you have a combined column (UserId & Status) and query using countif agains such values (for example 123success, 456fail). There may be a more elegant solution, but I don't see it now
@user2108935, if you have excel 2010 or later, COUNTIFS uses multiple criteria

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.