excel vba UDF在数组循环中

时间:2016-07-06 23:50:53

标签: arrays excel vba udf

我有一个只需要一个sumif的UDF。当我在一个单元格或一个"中使用它时,它适用于范围XYZ"循环但不是当我通过数组循环时。

我在A和B列中有一张包含帐户和项目ID编号列表的工作表,然后我添加了来自多个来源和公式的大约20列数据。我正在做这样的事情:

Dim array() as variant, ACCT as string, ID as string, lr as long
lr = Range("A1048576").end(xlup)
array=Range("A1:Z" & lr)

For i=1 to ubound(array)
ACCT=array(i,1):ID=array(i,2)
array(i,3)=DataSource1(ACCT,ID)
array(i,4)=DataSource2(ACCT,ID)

等...

我的DataSource1函数没有问题,但DataSource2函数返回0.两个函数几乎相同,只是DataSource2使用find来构建动态范围,因为列并不总是以相同的顺序。就像我说的那样,如果我通过范围内的每个单元循环而不是使用数组,它就可以工作。

Function DataSource2_Qty(ACCT As String, ID As String)

Dim rng As Range, lr As Long, ACCTS As Range, DATA As Range, _
        IDs As Range, Qty As Range, DATASht as Worksheet

Set DATASht = Sheets("DataSource2_SECURITY_DATA")
Set DATA = DATASht.UsedRange

lr = DATA.Rows.Count

Set rng = DATA.Cells.Find("Account", searchorder:=xlByColumns, Lookat:=xlWhole)
    Set ACCTS = DATASht.Range(DATA.Cells(1, rng.Column), DATA.Cells(lr, rng.Column))

Set rng = DATA.Cells.Find("Security Id", searchorder:=xlByColumns, Lookat:=xlWhole)
    Set IDs = DATASht.Range(DATA.Cells(1, rng.Column), DATA.Cells(lr, rng.Column))

Set rng = DATA.Cells.Find("Quantity", searchorder:=xlByColumns, Lookat:=xlWhole)
    Set Qty = DATASht.Range(DATA.Cells(1, rng.Column), DATA.Cells(lr, rng.Column))

DataSource2_Qty = Application.SumIfs(Qty, IDs, ID, ACCTS, ACCT)

End Function

0 个答案:

没有答案