2015-06-18 144 views
1

enter image description hereVBA SUM可變範圍

我想要一個代碼來將變量行加起來,如果滿足某些條件。 例如如果A12是數字並且B12是空的,則在單元格C12中插入一個公式以便求和C3:C11。 然後在C22和C30執行相同的操作。 我遇到的問題是不知道如何定義起始行。

Sub Test() 
Dim y As Variant 
Dim r As Variant 
Dim StartRow As Variant 

    LastRow = Range("C" & Rows.Count).End(xlUp).Row 
     For y = 3 To 500 
      For r = 1 To LastRow 

      If InStr(1, Cells(r, 1), "Amount") Then 
       StartRow = r 

      If IsNumeric(Cells(y, 1)) And IsEmpty(Cells(y, 2)) Then 
      Cells(y, 3).Formula = "=SUM(C" & StartRow + 1 & ":C" & y - 1 & ")" 
      End If 
     End If 
     Next r 
    Next y 

End Sub 
+0

你可以只用一個額外的列,而無需VBA ... –

+0

@LS_dev由於這只是我的整個代碼部分做到這一點,所以我想VBA代碼來執行此,可以你請幫忙?^^ –

回答

3
Sub Test() 
Dim y As Variant 
Dim firstRow As Variant 
Dim lastRow As Variant 
lastRow = Range("C" & Rows.Count).End(xlUp).Row 
firstRow = Cells(lastRow, 3).End(xlUp).Row 
If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then 
    Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")" 
End If 
For y = firstRow To 3 Step -1 
    lastRow = Cells(y, 3).End(xlUp).Row 
    firstRow = Cells(lastRow, 3).End(xlUp).Row 
    If firstRow < 3 Then firstRow = 3 
    If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then 
     Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")" 
    End If 
    y = firstRow 
    If firstRow = 3 Then Exit Sub 
    Next y 
End Sub 
+0

嗨安倍,非常好!有用!但是,我可以知道如何插入這種情況嗎? '如果是數字(單元格(y,1))和空格(單元格(y,2))則' –

+0

編輯答案以包含該內容。讓我知道如果它不起作用。我沒有測試它。 –

+0

嗨安倍,這個作品完美!但...仍然是一個問題,C12中的公式變爲SUM(C1:C11),我想要的是C3:C11。我應該修改哪一部分? –