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

时间:2017-07-31 18:16:15

标签: excel vba excel-vba ms-office

如何使用for循环找到列中的最大值?

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

2 个答案:

答案 0 :(得分:1)

要获取C列中对应的值,其中A列为max:

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

enter image description here

但这可以通过工作表上的以下公式来完成:

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

enter image description here

答案 1 :(得分:0)

斯科特克拉纳的答案是迄今为止最好的选择。

如果你需要使用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