VBA:如何用特定字符串描述行

时间:2017-08-10 02:17:26

标签: excel vba loops sum

您好我正在尝试创建一个标识“B”列中特定字符串的循环,并对同一行的“D”列中的值进行求和。到目前为止,我已经能够识别“现金”但现在我不知道如何描述SAME行的“D”列并总结它。请帮忙!

以下是我到目前为止的这个循环。

Dim CD As Long
Dim text As String
Dim Z As Long

CD = 0

For Z = 1 To Range("B" & Rows.Count).End(xlUp).Row
    text = Range("B" & Z).Value
    If Left(text, 4) = "Cash" Then
        Sum.... 

2 个答案:

答案 0 :(得分:2)

你当然可以这样做:

For Z = 1 To Range("B" & Rows.Count).End(xlUp).Row
    text = cells(Z,2).Value
    If Left(text, 4) = "Cash" Then
         Sum.... Zum = Zum + cells(Z,4).value

但是,计算可以使用简单的工作表公式

完成
=SUMIF(B:B,"cash*",D:D)

答案 1 :(得分:1)

按照您提供的代码,这将是您正在寻找的:

Sub calculateSum()

    Dim CD As Long
    Dim text As String
    Dim Z As Long

    'Create a variable to store the sum and set its value to 0.
    Dim sum As Double 
    sum = 0

    CD = 0

    For Z = 1 To Range("B" & Rows.Count).End(xlUp).Row
    text = Range("B" & Z).Value
        If Left(text, 4) = "Cash" Then
            'Increase the sum by the value stored in column D on the same row.
            sum = sum + Range("D" & Z).Value
        End If
    Next Z

    'Display the final result (sum).
    MsgBox "Sum: " & sum

End Sub