【发布时间】:2022-01-23 12:52:28
【问题描述】:
我想定义一个 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
【问题讨论】:
-
哪行代码给出了这个错误?为什么使用
Variant而不是Range? ...? -
@Dominique 我在输入公式的单元格中得到
#VALUE,代码没有错误 -
你的意思是
nRows = matrix.Count和nRows = matrix.Rows.Count一样吗? -
该错误意味着函数在以 UDF 形式调用时出现错误