在所有工作簿的行中查找最高编号

时间:2019-09-11 18:57:39

标签: excel vba

在工作簿的所有标签中的确定行(即第10行)中找到前5个最高的数字(值)。返回“选项卡名称”和值。

Sub ShowMinMax()
    Dim vMax

        vMax = Application.WorksheetFunction.Max(Rows("10"))

    MsgBox "Maximum = " & vMax, vbInformation, "GetMax Values"
End Sub

预期结果应为: “选项卡名称” maxValue1 “选项卡名称” maxValue2 ... “选项卡名称” maxValue5

1 个答案:

答案 0 :(得分:1)

这将迭代工作表并返回前五个数字及其各自的工作表。

Sub ShowMinMax()

    Dim MaxArr(1 To 5, 1 To 2) As Variant
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        Dim lstColumn As Long
        lstColumn = ws.Cells(10, ws.Columns.Count).End(xlToLeft).Column

        Dim rowArr As Variant
        rowArr = ws.Range(ws.Cells(10, 1), ws.Cells(10, lstColumn)).Value
        Dim i As Long
        For i = 1 To lstColumn
            If Not IsEmpty(rowArr) Then
            If IsNumeric(rowArr(1, i)) Then
                Dim j As Long
                For j = 1 To 5
                    If rowArr(1, i) > MaxArr(j, 2) Then
                        Dim k As Long
                        For k = 5 To j + 1 Step -1
                            MaxArr(k, 2) = MaxArr(k - 1, 2)
                            MaxArr(k, 1) = MaxArr(k - 1, 1)
                        Next k
                        MaxArr(j, 2) = rowArr(1, i)
                        MaxArr(j, 1) = ws.Name
                        Exit For
                    End If
                Next j
            End If
            End If
        Next i
    Next ws

    'Change line below to the correct output range        
    Worksheets("Sheet20").Range("A15").Resize(5, 2).Value = MaxArr


End Sub

这是我执行以上操作后得到的:

enter image description here