Search code examples
excelvbaloopssumifs

Sum multiple columns in one if the columns contain specific words


I want to sum multiple columns that contain the words "SM" in one column. The code return only the values of the last column that contains the words "SM", it dosen't retrun the total. Here is the code :

Sub UHD_Values()

Dim i, x As Long

With Sheets("BDD")

LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column

For i = 2 To LastRow
For x = 9 To LastCol

If InStr(1, .Cells(x).Value, "SM") Then Sheets("RR").Cells(i, 5) = .Cells(i, x)

Next x, i

End With

End Sub

Here is the data :

enter image description here


Solution

  • If InStr(1, .Cells(x).Value, "SM") Then Sheets("RR").Cells(i, 5) = .Cells(i, x)
    

    should be

    If InStr(1, .Cells(x).Value, "SM") Then Sheets("RR").Cells(i, 5) = Sheets("RR").Cells(i, 5) +  .Cells(i, x)
    

    You were continually overwriting cells(i,x) in each loop