2017-08-10 77 views
0

嗨我試圖創建一個循環,標識列「B」中的特定字符串,並彙總同一行的列「D」中的值。到目前爲止,我已經能夠識別「現金」,但現在我不知道如何描述同一行的列「D」並對其進行總結。請幫忙!VBA:如何描述具有特定字符串的行

下面是我到目前爲止的這個循環。

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.... 

回答

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 
+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) 
+0

或者在VBA中通過'Application.SumIf([B:B],「cash *」,[D:D]),如果他需要VBA中的數字(在ws中這樣做對我來說更有意義) –

+0

你的幫助!運作良好。 –