我想定義一個 VBA 函式:
- 回傳矩陣主對角元素的列向量;
- 回傳一個方對角矩陣,其中向量元素位于主對角線上;
- 自動回傳矩陣/向量,無需按 Ctrl Shift Enter;
我正在處理此代碼:
Public Function DIAG(matrix As Variant) As Variant
Dim i As Long
Dim j As Long
Dim nRows As Long
Dim nCols As Long
Dim tempArray As Variant
nRows = matrix.Rows.Count
nCols = matrix.Columns.Count
For i = 1 To nRows
For j = 1 To nCols
If i = j Then
tempArray(i) = matrix(i, j)
End If
Next j
Next i
DIAG = tempArray
End Function
這僅用于該功能的第一個目的,但它不起作用。我得到:
#VALUE
uj5u.com熱心網友回復:
您的函式在作為 UDF 呼叫時回傳這樣的錯誤,如果我正確理解您想要什么,請使用下一個改編的函式:
Public Function DIAG(matrix As Range) As Variant
Dim i As Long, j As Long, k As Long, nRows As Long, nCols As Long
Dim tempArray As Variant
nRows = matrix.Count: nCols = matrix.Columns.Count
ReDim tempArray(nRows * nCols) 'without this step it will return an error when try loading
For i = 1 To nRows
For j = 1 To nCols
If i = j Then
tempArray(k) = matrix(i, j): k = k 1
End If
Next j
Next i
ReDim Preserve tempArray(k - 1) 'preserving only the elements keeping data
DIAG = tempArray
End Function
中間陣列應該是 ReDim,然后只保留保留資料的元素......
結束陳述句(@Dominique 建議):如果你創建了一個用戶定義的函式,稱為 UDF,那么首先通過在宏中呼叫它來測驗它,只有當它回傳你需要的東西,沒有任何錯誤時,你才可以呼叫它直接從一個單元格。
uj5u.com熱心網友回復:
我認為您的應用程式的結構有問題:您確定您的函式所在的模塊可以從您的 Excel 作業簿訪問嗎?
舉個例子,我做了一個類似的函式,我在我的 Excel 作業簿中使用它(在一個單元格中,我輸入了公式=DIAG(J5:Q25))并且一切正常,特此截圖:

糟糕,我剛剛嘗試了其他方法,但出現相同的錯誤訊息:
Public Function DIAG(matrix As Variant) As Variant
Dim tempArray As Variant
tempArray(1) = 1
tempArray(2) = 2
DIAG = tempArray
End Function
你確定你可以回傳整個矩陣甚至單維陣列作為函式的回傳值,并那么容易地呼叫它嗎?
為了您的資訊,我嘗試了這個,=DIAG(J5:Q25)在一個單元格中使用,在兩個單元格中使用,并作為陣列公式使用。
uj5u.com熱心網友回復:
@FaneDuru 的代碼確實幫助了我,但我以這種方式成功地編碼了我的 UDF:
Public Function DIAG(matrix As Range) As Variant
Dim i As Long, j As Long, nRows As Long, nCols As Long
Dim tempArray As Variant
nRows = matrix.Rows.Count
nCols = matrix.Columns.Count
If nCols = 1 Then
ReDim tempArray(nRows - 1, nRows - 1)
For i = 1 To nRows
tempArray(i - 1, i - 1) = matrix(i)
Next i
Else
If nCols = nRows Then
ReDim tempArray(nRows - 1, 0)
For i = 1 To nRows
For j = 1 To nCols
If i = j Then
tempArray(i - 1, 0) = matrix(i, j)
End If
Next j
Next i
Else
tempArray = CVErr(xlErrValue)
End If
End If
DIAG = tempArray
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/392500.html
