如果列包含特定单词,则将多个列合二为一

Sum multiple columns in one if the columns contain specific words

我想对一列中包含单词 "SM" 的多列求和。代码 return 仅包含包含单词 "SM" 的最后一列的值,它不会重新计算总数。这是代码:

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

这是数据:

应该可行:

Sub UHD_Values()

Dim lastRow As Long, lastCol As Long
Dim i As Long, 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(i, x).Value, "SM") > 0 Then
                Sheets("RR").Cells(i, 5) = .Cells(i, x).Value
            End If

        Next x
    Next i

End With

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

应该是

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

您在每个循环中不断覆盖单元格 (i,x)