VBA:For 循环查找列中的最大值

VBA: For Loop to find maximum value in a column

您将如何使用 for 循环查找列中的最大值?

我希望能够将最大值存储在变量中。

Scott Craner 的回答是迄今为止最好的选择。

如果你需要使用 for 循环,像这样...

将firstRow的值设置为包含第一行数据的行号。 columnNumber 是包含您正在计算最大值的项目的列的索引:

Dim sheet As Worksheet
Dim i As Integer
Dim firstRow As Integer
Dim columnNumber As Integer
Dim max As Integer

firstRow = 1
columnNumber = 6

Set sheet = ActiveSheet

If sheet.UsedRange.Rows.Count <= 1 Then max = NaN Else max = sheet.Cells(firstRow, columnNumber)

For i = firstRow + 1 To sheet.UsedRange.Rows.Count
    If sheet.Cells(i, columnNumber) > max Then max = sheet.Cells(i, columnNumber)
Next

sheet.Cells(1, 1) = max

获取A列最大值的C列对应值:

dim t as long
dim rslt as string
With Worksheets("RESOURCE") ' Change to your sheet
    t = Application.WorksheetFunction.Match(Application.WorksheetFunction.Max(.Range("AX6:AX29")),.Range("AX6:AX29"),0)
    rslt = .Range("A6:A29")(t)
    Debug.Print rslt
End With


但这可以通过 sheet 上的以下公式来完成:

=INDEX(RESOURCE!A6:A29,MATCH(MAX(RESOURCE!AX6:AX29),RESOURCE!AX6:AX29,0))