如何正确偏移行以在 VBA 中的列中查找最大数字?

How do I Offset Rows correctly to Find the highest number in a Column in VBA?

我正在尝试 运行 VBA 中的这段代码,找出哪一行在 'A' 列中的编号最大?但它不起作用。有人可以帮忙吗?以下是代码:

Sub ForNextDemo()
Dim MaxVal As Double
Dim Row As Long

MaxVal = WorksheetFunction.Max(Range("A:A"))
For Row = 1 To Rows.Count

If Range("A1").Offset(1, 0).Value = MaxVal Then
Range("A1").Offset(1, 0).Activate

MsgBox "Maximum Value is in" & Row

Exit For
End If
Next Row
End Sub

您的代码失败,因为您总是检查同一个单元格。无论 row 具有哪个值,Range("A1").Offset(1, 0) 将始终检查单元格 A2(A1 下面的 1 行)

你的意思大概是Range("A1").Offset(row, 0)

但是,使用 Match 函数有一种更简单(也更快)的方法来获取具有最大值的行。

一个建议:你应该总是告诉VBA应该使用哪个sheet。当你写 Range(A1) 时,它会使用当前有效的 sheet。这并不总是你想要的。相反,使用例如 ThisWorkbook.Sheets(1)(存储代码的工作簿的第一个 sheet)。您也可以使用 sheet 名称,例如 ThisWorkbook.Sheets("Sheet1")

Dim MaxVal As Double
Dim Row As Long

With ThisWorkbook.Sheets(1)
    Dim r As Range
    Set r = .Range("A:A")
    MaxVal = WorksheetFunction.max(r)
    Row = WorksheetFunction.Match(MaxVal, r, 0)
    Debug.Print "The maximum value is " & MaxVal & " and it is found in row " & Row
End With

获取最大值及其第一次出现的行

  • 如果列中没有错误值,则可以避免循环。
Sub ForNextDemo()
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim MaxVal As Variant ' could be an error value
    Dim MaxRow As Long
    
    With ws.Range("A:A")
        
        If Application.Count(.Cells) = 0 Then
            MsgBox "There are no numbers in the column.", vbCritical
            Exit Sub
        End If
        
        MaxVal = Application.Max(.Cells)

        If IsError(MaxVal) Then
            MsgBox "There are error values in the column.", vbCritical
            Exit Sub
        End If
        
        MaxRow = Application.Match(MaxVal, .Cells, 0)

        ' Select and scroll to the first 'max' cell.
        Application.Goto .Cells(MaxRow), True
    
    End With
    
    MsgBox "The maximum value is " & MaxVal & "." & vbLf _
        & "Its first occurrence is in row " & MaxRow & ".", vbInformation
    
End Sub