VBA Excel在范围内查找日期,并在其中进行计算

时间:2012-12-08 22:14:27

标签: excel vba

我正在执行VB功能,以使用不同的类别对指定时间段内的累积金额进行排序。目标是人事帐户费用。

例如,我在A列的表格“tmp”中有一些日期,在B栏中有一个类别(例如,薪水,运输......),在C栏中有值。

我想定义一个函数,我试图设置:

Function Cumulatif(Categorie As String, Debut As Date, Fin As Date) As Double
    ' Do the sum of a category between a starting and ending date specified 
    Dim Operations As Variant
    Dim SpecificSum As Double
    Dim i As Integer
    Operations = ThisWorkbook.Sheets("tmp").Range("A1:C3")
    For Each Row In Operations.Rows
        SpecificSum = 0
    Next
    Cumulatif = SpecificSum
End Function

但我真的不知道如何从另一张表中获取值并在范围内进行循环以设置此总和。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

  1. 对操作的分配需要是一个对象赋值,意思是:使用Set(不是Let / default)。

    设置操作= ThisWorkbook.Sheets(“tmp”)。范围(“A1:C3)

  2. 您可以从其他工作表中获取值(假设您的意思是“tmp”),如下所示

    SpecificSum = SpecificSum + Row.Cells(1, 1)
    
  3. 我认为你最好让函数获取一个额外的范围参数并提供Sheet1!A作为参数;这样Excel就会知道何时需要重新计算。

    Function Cumulatif(Categorie As String, Debut As Date, Fin As Date, Operations As Range) As Double
        ' Do the sum of a category between a starting and ending date specified
        'Dim Operations As Variant
        Dim SpecificSum As Double
        Dim i As Integer
        'Set Operations = ThisWorkbook.Sheets("Sheet1").Range("A2:C3")
        For Each Row In Operations.Rows
            SpecificSum = SpecificSum + Row.Cells(1, 1)
        Next
        Cumulatif = SpecificSum
    End Function
    

    使用这样的公式打电话给Cumulatif:

    =Cumulatif("hello9","10/1/2010", "10/31/2010",Sheet1!A2:A3)