在Excel VBA中返回绝对值的行和列

时间:2018-10-29 14:15:15

标签: excel vba excel-vba excel-formula

我的问题是为什么它不喜欢AddressOfMaxRow和AddressOfMaxCol变量?我是白痴吗?

Function MaxABS(rng, AddressOfMaxRow, AddressOfMaxCol, MaxVal)

Dim arr As Variant

arr = rng.Value

For i = 1 To UBound(arr, 1)

    For j = 1 To UBound(arr, 2)
        arr(i, j) = VBA.Abs(arr(i, j))
    Next
Next

MaxVal = Application.WorksheetFunction.Max(arr)


AddressOfMaxRow = WorksheetFunction.Index(arr, WorksheetFunction.Match(WorksheetFunction.Max(arr), arr, 0)).Cells.Row

AddressOfMaxCol = WorksheetFunction.Index(arr, WorksheetFunction.Match(WorksheetFunction.Max(arr), arr, 0)).Cells.Column

End Function

1 个答案:

答案 0 :(得分:1)

也许是这样,它返回“ max”单元格的地址(例如$D$9),但可以根据需要进行调整以返回行和列。

请注意,这假设rng仅包含数字值,例如,如果有文本,可以增强为不会出错。如果最大值出现多次,它将仅返回第一个最大值地址。

Function MaxABS(rng As Range) As String
    Dim arr As Variant
    arr = rng.Value

    Dim i As Long, j As Long
    Dim tempMax As Double
    Dim tempRow As Long, tempCol As Long

    For i = 1 To UBound(arr, 1)
        For j = 1 To UBound(arr, 2)
            arr(i, j) = VBA.Abs(arr(i, j))
            If arr(i, j) > tempMax Then
                tempMax = arr(i, j)
                tempRow = i
                tempCol = j
            End If
        Next j
    Next i

    MaxABS = rng.Cells(tempRow, tempCol).Address
End Function

要返回行和列(由于未指定所需的输出格式,因此用逗号分隔),请替换最后一行

MaxABS = rng.Cells(tempRow, tempCol).Address

具有以下内容:

With rng.Cells(tempRow, tempCol)
    MaxABS = .Row & "," & .Column
End With

示例输出为9, 4,而不是$D$9