在VBA中打印矩阵

时间:2018-03-13 13:19:08

标签: excel vba excel-vba

For example please open this如果有N * N矩阵,则给出R(行)。因此程序将在Rth行中找到最小值,然后用9999替换该特定列。我收到#value错误。如何纠正这个? 我认为定义一个数组有一些错误。 请帮助我。

Function abc(N As Range, R As Integer) As Range
    Dim c As Integer, i As Integer, min As Integer, ci As Integer, a As Integer,
    j As Integer, y As Integer, z As Integer

    a = N.Rows.Count
    c = N.Columns.Count

    Dim ab(1 To 1000, 1 To 1000) As integer

    min = N(R, 1)
    ci = 1

    For i = 1 To c
        If N(R, i) < min Then
            min = N(R, i) And ci = i
        End If
    Next i

    For y = 1 To a
        For z = 1 To c
            If z = ci Then
                ab(y, z) = 9999
            Else
                ab(y, z) = N(y, z)
            End If
        Next z
    Next y

    abc = ab
End Function

2 个答案:

答案 0 :(得分:0)

这需要是VBA吗?可以使用此公式(使用您的样本图像,将此公式放在单元格D1中并上下复制):

=IF(COLUMN(A1)=MATCH(MIN(INDEX($A$1:$B$2,2,0)),INDEX($A$1:$B$2,2,0),0),5432,INDEX($A$1:$B$2,ROW(A1),COLUMN(A1)))
  • $A$1:$B$2的两个实例更改为公式应该进行的实际范围
  • 5432更改为您实际想要返回的数字(我从您的示例图片中获得5432,但您的UDF显示为9999)

答案 1 :(得分:0)

除了输出问题之外,您的代码不是您的问题措辞

所以你要么

  • 必须用9999

    替换行中的最小值

    因此您的代码可以缩减为

    Function abc(N As Range, R As Integer) As Variant
        Dim a As Long, c As Long, j As Long, min As Long, cj As Long
    
        Dim ab As Variant
        ab = N.value
    
        a = UBound(ab, 1)
        c = UBound(ab, 2)
    
        min = ab(R, 1)
        cj = 1
        For j = 1 To c
            If ab(R, j) < min Then
                min = ab(R, j)
                cj = j
            End If
        Next
    
        ab(R, cj) = 9999
    
        abc = ab
    End Function
    
  • 或者您必须将内容与给定行最小值匹配的所有范围单元格更改为后者

    Function abc2(N As Range, R As Integer) As Variant
        Dim a As Long, c As Long, i As Long, j As Long, min As Long
    
        Dim ab As Variant
        ab = N.value
    
        a = UBound(ab, 1)
        c = UBound(ab, 2)
    
        min = ab(R, 1)
        For j = 1 To c
            If ab(R, j) < min Then min = ab(R, j)
        Next
    
        For i = 1 To a
            For j = 1 To c
                If ab(i, j) = min Then ab(i, j) = 9999
            Next
        Next
    
        abc2 = ab
    End Function