数组函数的组成

时间:2014-01-16 11:47:41

标签: arrays vba

我担心返回数组的函数组成。

例如,让我们定义

Function APTranspose(X As Variant) As Variant

Dim v() As Variant
Dim r, c, rc, cc As Integer

r = X.rows.count
c = X.Columns.count

ReDim v(1 To c, 1 To r)

For cc = 1 To c
    For rc = 1 To r
    v(cc, rc) = X(rc, cc)
    Next
Next

APTranspose = v

End Function

和无用的功能

Function Identity(X As Variant) As Variant

Dim res As Variant

res = APTranspose(X)

res = APTranspose(res)

Identity = res

End Function

现在很明显,Function(x)应该是x本身。

然而我得到#VALUE!在Excel上。一般来说,我不能组成数组函数。为什么???

谢谢!

1 个答案:

答案 0 :(得分:0)

出现问题的原因是,当您在行APTranspose中调用res = APTranspose(X)时,它正常工作,因为XRange类型的对象,并且它具有{{1}等属性}和X.rows.count。但是当您在行X.Columns.count - res = APTranspose(res)中调用此函数时,它不是res对象,它是一个数组,并且它没有属性RangeX.rows.count 。这会触发错误。

您可以使用以下代码:

X.Columns.count

<强> UPD:

或者您可以使用以下功能:

Function APTranspose(X As Variant) As Variant
    APTranspose = WorksheetFunction.Transpose(X)
End Function

Function Identity(X As Variant) As Variant
    Dim res As Variant
    res = APTranspose(X)
    res = APTranspose(res)
    Identity = res
End Function