2012-08-23 99 views
0

嗨我需要一個宏來計算的發生#根據一些條件。這裏是數據表的樣本:Excel宏來計算價值基礎上的條件

ID  Paydate  # of payments 
1  5/1/2011   3 
1  5/1/2011   3 
1  3/1/2011   2 
1  2/1/2011   1 
2  6/12/2011   3 
2  5/12/2011   2 
2  4/12/2011   1 
3  4/25/2011   2 
3  3/25/2011   1 

我想算一個支付ID已經由該日期的#(第3列是什麼,我需要)。例如,對於ID = 1和paydate = 5/1/2011,已經有3次付款,對於ID = 1和paydate = 3/1/2011,有2次付款。宏應計算小於或等於當前日期的付款次數,如果有多個具有相同日期的ID,則不會增加計數。

如果有一種方法可以做到這一點的公式,這將是偉大的,但它似乎太複雜。任何幫助將非常感激。

+2

whathaveyoutried.com – ApplePie

+0

[GIYF(http://www.google.com),你有很好的關鍵字。嘗試一下,讓我們知道如果你卡住了。 –

回答

3

你不需要宏或vba。

=COUNTIFS(A:A,A2,B:B,"<=" & B2) 

把它放在C2中。

0

沒有足夠的信息可以繼續,例如你有沒有找到日期以及你在哪裏找到id。所以如果我做了一些假設,我可以寫一些這樣的VBA。另外這是一個比較長,可以細分到另一個函數來獲取用戶的響應

Option Explicit 
Sub numberOfPayments() 
On Error Resume Next 
Dim iRow As Integer 
Dim iCol As Integer 
Dim dtDate As Date 
Dim iID As Integer 
Dim sResponse As String 
Dim iNumberOfPayments As Integer 

'initialize the variables 
iNumberOfPayments = 0 
iRow = 2 
iCol = 1 

'get the date 
sResponse = InputBox("Calculate for what date? (M/D/YYYY)", "Get Payment Date") 

'check to make sure its a valid date 
If IsDate(sResponse) Then 
    'set date we are looking for 
    dtDate = CDate(sResponse) 
Else 
    MsgBox "You must enter a valid date" 
    Exit Sub 
End If 

'reset the response 
sResponse = "" 
'get the ID 
sResponse = InputBox("Calculate for what ID?", "Get Payment ID") 

'set the ID to look for 
iID = CInt(sResponse) 

'if the conversion failed there will be an error 
If Err.Number <> 0 Then 
    MsgBox "You must enter a valid ID" 
    Exit Sub 
End If 

'assumes you have data in each cell 
Do While Cells(iRow, iCol).Value <> "" 
    'check the ID 
    If Cells(iRow, iCol).Value = iID Then 
     'this is done as not sure if the column is formatted as a date or just text 
     If IsDate(Cells(iRow, iCol + 1).Text) Then 
      If dtDate <= CDate(Cells(iRow, iCol + 1).Text) Then 
       'add the payments 
       iNumberOfPayments = iNumberOfPayments + Cells(iRow, iCol + 2).Value 
      End If 
     End If 
    End If 
    'move to the next row 
    iRow = iRow + 1 
Loop 
'inform them of the number of payments 
MsgBox "there are " + Str(iNumberOfPayments) + " total payments." 

End Sub