Excel宏根据条件计算值

时间:2012-08-23 01:05:51

标签: excel excel-vba vba

我需要一个宏来计算基于某些条件的出现次数。这是数据表的示例:

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 个答案:

答案 0 :(得分:3)

您不需要宏或vba。

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

把它放在C2中。

答案 1 :(得分: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