2014-01-16 110 views
0

我很關心返回數組的函數組成。數組函數的組合

例如,讓我們定義

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 

現在很明顯,功能(X)應該是X本身。

但是我得到#VALUE!在Excel上。一般來說,我不能編寫數組函數。這是爲什麼??

謝謝!

+0

在調用此函數在Excel? –

回答

0

該問題的原因是,當你調用排隊res = APTranspose(X)APTranspose它工作正常,因爲XRange類型的對象,它有一個像X.rows.countX.Columns.count性能。但是當你在res = APTranspose(res) - res中調用該函數時,它不是Range對象,它是一個數組,它沒有屬性X.rows.countX.Columns.count。這會觸發一個錯誤。

您可以使用下面的代碼:

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 

UPD:

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

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

    If TypeOf X Is Range Then 
     r = X.Rows.Count 
     c = X.Columns.Count 
    Else 
     r = UBound(X, 1) 
     c = UBound(X, 2) 
    End If 
    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 Range) As Variant 

    Dim res() As Variant 

    res = APTranspose(X) 
    res = APTranspose(res) 
    Identity = res 
End Function 
+0

那麼如何檢索數組的行數/列數呢? – user3202334

+0

看到我更新的unswer –

+0

謝謝,但這個APTranspose不會工作 – user3202334