excel vba about sum up number of multiple words

huiyin9218

Board Regular
Joined
Aug 7, 2018
Messages
53
Hi,

How do i write a code to count total of "blue" and "red" in each school? The sum of blue and red have to be written at the cell next to the school.
Colors other than blue and red are ignored. The rows in each school is inconsistent.


AB School4
Blue
Blue
Red
Red
CD School1
Red
Yellow

<tbody>
</tbody>

I would be so grateful for your help.
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
If the first column is A and Result in Column B then try the below code :
Code:
Sub countBlueRed()
    Dim i           As Long
    Dim j           As Long
    Dim Counter     As Long
    Dim iCount      As Long
    iCount = Range("A" & Rows.count).End(xlUp).Row
    For i = 1 To iCount
        If InStr(UCase(Range("A" & i).Value), "SCHOOL") > 0 Then
            Counter = 0
            For j = i + 1 To iCount
               If InStr(UCase(Range("A" & j).Value), "SCHOOL") > 0 Then Exit For
                    If UCase(Range("A" & j).Value) = "BLUE" Or UCase(Range("A" & j).Value) = "RED" Then
                        Counter = Counter + 1
                    End If
            Next j
            Range("B" & i).Value = Counter
        End If
    Next i
End Sub
 
Upvote 0
Another option
Code:
Sub SumSchools()
   Dim Rng As Range
   With Range("B1", Range("A" & Rows.Count).End(xlUp).Offset(, 1))
      .Value = Evaluate(Replace("if(isnumber(search(""school"",@)),true,"""")", "@", .Offset(, -1).Address))
      For Each Rng In .SpecialCells(xlBlanks).Areas
         Rng.Offset(-1).Resize(1).Value = Application.CountIf(Rng.Offset(, -1), "red") + Application.CountIf(Rng.Offset(, -1), "blue")
      Next Rng
   End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,946
Messages
6,122,401
Members
449,081
Latest member
JAMES KECULAH

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top