使用VBA将函数结果数组输出到工作表

时间:2017-08-01 17:43:51

标签: arrays excel vba excel-vba function

场景:我有一个函数可以对集合的组件权重执行上限过程。

问题:当我尝试将结果输出数组输出到excel工作表时,我不断收到值错误(在应用该函数的excel单元格上)

我已尝试过的内容:我尝试了Excel VBA function to print an array to the workbook

中的答案

但我仍然得到同样的错误

问题:如何正确执行此程序?事实上我使用的函数对此操作有问题吗?

代码的相关部分:(删除了昏暗的部分和其他基本操作以保持问题的简洁性)

Function Capping(ISIN As Range, Sector As Range, Weights As Range, W1 As Double, W2 As Double) As Variant

le = UBound(ArISIN)
ReDim Preserve ArCap(le, 8, 1)

For c = 1 To le
    ArCap(c, 1, 1) = ArISIN(c, 1)
    ArCap(c, 2, 1) = ArSector(c, 1)
    ArCap(c, 3, 1) = ArWeight(c, 1)
Next c

For c = 1 To le
    s = 0
    For i = 1 To le
        If ArCap(c, 2, 1) = ArCap(i, 2, 1) Then
            s = s + ArCap(i, 3, 1)
        End If
    Next i
    ArCap(c, 4, 1) = s
Next c

For c = 1 To le
    If ArCap(c, 4, 1) >= W2 Then
        ArCap(c, 5, 1) = 0.03
        ArCap(c, 6, 1) = 0.03 / ArCap(c, 3, 1) * ArCap(c, 4, 1)
    Else
        ArCap(c, 5, 1) = "Not Capped"
    End If
Next c

suc = 0
scap = 0
For c = 1 To le
    If ArCap(c, 5, 1) <> "Not Capped" Then
        scap = scap + ArCap(c, 6, 1)
    Else
        suc = suc + ArCap(c, 3, 1)
    End If
Next c

For c = 1 To le
    If ArCap(c, 5, 1) = 0.03 Then
        ArCap(c, 7, 1) = ArCap(c, 6, 1)
    Else
        ArCap(c, 7, 1) = ArCap(c, 3, 1) / suc * (1 - s)
    End If
Next c

For c = 1 To le
    s = 0
    For i = 1 To le
        If ArCap(c, 2, 1) = ArCap(i, 2, 1) Then
            s = s + ArCap(i, 7, 1)
        End If
    Next i
    ArCap(c, 8, 1) = s
Next c

ReDim Preserve OutArray(le, 0)
For c = 1 To le
    OutArray(c, 0) = ArCap(c, 7, 1)
Next c

'this is where I am having problems:    
ActiveSheet.Range("A4:UC4").Value = WorksheetFunction.Transpose(OutArray)

2 个答案:

答案 0 :(得分:1)

您应该通过函数返回值,而不是直接将其写入工作表。最后一行看起来像:

Capping = WorksheetFunction.Transpose(OutArray)

您将在预期的单元格中将此函数称为公式。否则你应该把它写成子程序而不是函数。

答案 1 :(得分:1)

您正在将结果写在一行上,因此一维数组足以容纳数据:

ReDim OutArray(1 To le)

For c = 1 To le
    OutArray(c) = ArCap(c, 7, 1)
Next

ActiveSheet.Range("A4").Resize(1, le) = OutArray