如果列中包含特定单词,则将多个列合计

时间:2019-09-06 11:10:51

标签: excel vba loops sumifs

我想对一列中包含单词“ SM”的多列求和。该代码仅返回包含单词“ 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

以下是数据:

enter image description here

2 个答案:

答案 0 :(得分:0)

应该可以:

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

答案 1 :(得分:0)

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)