1

I would like to create a function which loops over certain cell values. If the value contains an "X", the count should increase by 1.

The syntax should be something like this:

 Sub CountVars()

 Dim range As Variant
 Dim ranges As Variant

 Dim count as Integer

 'set array with ranges
 range = Array("c3", "f3", h3)

 For Each range In ranges

   count = 0
   'if range = "X" then
   count = count + 1
   End If    
 Next

But I cant get this working. Any thoughts on how I can achieve my goal?

1 Answer 1

2

You can define your ranges within the Range() function directly. No need for a string array. For example:

Dim r As Range, count As Long

For Each r In Range("C3,F3,H3")
    If r.Value = "X" Then count = count + 1
Next

Note that string comparison done this way is case-sensitive. If you need to check for x or X, you can convert to the same case or use a function like StrComp() with the vbTextCompare parameter.

If UCase$(r.Value) = "X" Then ...
' or
If StrComp(r.Value, "X", vbTextCompare) = 0 Then ...
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your reply. Your code gives me a compile error: (wrong number of arguments or invalid property assignment. Any thoughts where this goes wrong?
On which line? I don't see any issues here.
it gives an errror right at the start where I declary my funcion -> Sub cDays()
Are you attempting to pass a parameter to your Sub? Because you haven't defined any.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.