我有一个表格,其数据类似于下面的
A B C D E
1 London NY LA Chicago
2 Population 11 18 16 12
我有以下代码来获取最大值:(成功)
Dim Rng As Range
Dim Ray
Dim Max As Integer
Set Rng = Range(Range("B2"), Range("E2").End(xlUp))
Ray = Rng.Value
Max = Application.Max(Ray)
然后,我试图获得具有最大值的列。我的目标是让“C”或C1能够知道NY(C1)是具有最大值的那个。
我会尝试以下但不能正常工作
For Each cell In Rng
If cell.Value = Max Then
MaxAddress = cell.Address
Exit For
End If
Next cell
答案 0 :(得分:1)
这与你的代码有关,应该有效:
Option Explicit
Public Sub TestMe()
Dim Rng As Range
Dim Ray As Variant
Dim MaxValue As Double
Dim MaxCell As Range
Dim cell As Range
Set Rng = ActiveSheet.Range(Range("B2"), Range("E2").End(xlUp))
Ray = Rng.value
MaxValue = Application.Max(Ray)
For Each cell In Rng
If cell = MaxValue Then
Set MaxCell = cell
Exit For
End If
Next cell
Debug.Print MaxCell.Address
Debug.Print MaxCell.Column
Debug.Print MaxCell.row
End Sub
还有其他方法,可能更好 - 例如创建一个单独的函数,为您提供一行中给定值的列。这个你可以使用很多。
答案 1 :(得分:0)
Option Explicit
Sub TestMax()
Dim oSheet As Worksheet
Dim oRange As Range
Dim maxValue As Integer
Dim oMaxCell As Range
Set oSheet = ActiveSheet
Set oRange = oSheet.Range("B2:E2")
maxValue = Application.Max(oRange.Value)
For Each oMaxCell In oRange.Cells
If CInt(oMaxCell.Value) = maxValue Then
Exit For
End If
Next oMaxCell
Debug.Print oMaxCell.Column
End Sub
根据其他数据,您可能不想使用整数
编辑:哎呀有人加快了