Excel - 用户定义函数:[输入 - 矢量],[输出 - 对角线上的条目的方形矩阵]

时间:2017-02-20 05:14:23

标签: excel vba user-defined-functions udf

如何在Excel中编写VBA函数,将输入向量(例如“A1”= 1,“B2”= 2,“C3”= 3)转换为对角线条目的方形矩阵,例如,“E1”= 1,“F1”= 0,“G1”= 0,“E2”= 0,“F2”= 2,“G2”= 0,“E3”= 0,“F3”= 0, “G3”= 3?提前谢谢。

我尝试使用以下代码:

Function Test2(X)
  Dim n As Integer
  n = WorksheetFunction.Count(X)
  ReDim Y(1 To n, 1 To n) As Integer
  Dim i As Integer, j As Integer
  For i = 1 To n
    For j = 1 To n
      If i = j Then Y(i, j) = X(i) Else Y(i, j) = 0
    Next j
  Next i
  Test2 = Y
 End Function

我作为数组函数输入了函数,但输出不正确。

2 个答案:

答案 0 :(得分:0)

我会仔细检查你是否正确输入了该功能(并确保你使用test2而不是测试或其他东西),因为它为我工作。还要记住,为了正确显示输出数组,您需要在输入功能之前选择整个输出范围,然后按CTRL+SHIFT+ENTER

enter image description here

答案 1 :(得分:0)

这确实有效:

Option Explicit

Function Test2(ByRef x() As Variant) As Variant
  Dim n As Integer
  n = WorksheetFunction.Count(x)
  ReDim y(1 To n, 1 To n) As Variant
  Dim i As Integer, j As Integer
  For i = 1 To n
    For j = 1 To n
       If i = j Then
        y(i, j) = x(i - 1)
       Else
        y(i, j) = 0
       End If
    Next j
  Next i
  Test2 = y
End Function


Sub checkTest2()
  Dim x() As Variant
  Dim y() As Variant

  x = Array(Cells(1, 1), Cells(2, 2), Cells(3, 3))
  y = Test2(x)

  Dim i As Integer, j As Integer
  For i = LBound(y, 1) To UBound(y, 1)
    For j = LBound(y, 2) To UBound(y, 2)
      Cells(i, j).Offset(0,4).Value = y(i, j)
    Next
  Next

End Sub