VBA 查找一列的最大值
时间: 2023-10-12 15:04:41 浏览: 80
您可以使用以下 VBA 代码来查找一列的最大值:
```vb
Function GetMaxValue(ByVal rng As Range) As Double
Dim cell As Range
Dim maxVal As Double
maxVal = rng.Cells(1).Value
For Each cell In rng.Cells
If cell.Value > maxVal Then
maxVal = cell.Value
End If
Next cell
GetMaxValue = maxVal
End Function
```
使用方法:将需要查找最大值的列作为参数传递给该函数即可。例如,如果您想在 A 列中查找最大值,可以使用以下公式:
```
=GetMaxValue(A:A)
```
相关问题
VBA 查找n列最大值
以下是 VBA 代码,可以查找指定范围内的 n 列最大值:
```vb
Sub FindMaxValues()
Dim rng As Range
Dim n As Integer
Dim maxValues() As Double
Dim i As Integer, j As Integer
'设置范围和列数
Set rng = Range("A1:E10")
n = 3
'初始化数组
ReDim maxValues(1 To n)
For i = 1 To n
maxValues(i) = -1E+20
Next i
'查找最大值
For i = 1 To rng.Rows.Count
For j = 1 To n
If rng.Cells(i, j).Value > maxValues(j) Then
maxValues(j) = rng.Cells(i, j).Value
End If
Next j
Next i
'输出结果
For i = 1 To n
MsgBox "第 " & i & " 列最大值为 " & maxValues(i)
Next i
End Sub
```
在上述代码中,我们首先设置了范围和列数,然后初始化了一个数组来存储最大值。接着,我们使用嵌套的循环遍历指定范围内的所有单元格,查找每一列的最大值,并将其存储到相应的数组元素中。最后,我们输出每一列的最大值。
VBA查找一列随机数的最大值
您可以使用以下VBA代码来查找一列随机数的最大值:
```
Function FindMax(rng As Range) As Double
Dim arr() As Variant
Dim i As Long
arr = rng.Value
FindMax = arr(1, 1)
For i = 2 To UBound(arr, 1)
If arr(i, 1) > FindMax Then
FindMax = arr(i, 1)
End If
Next i
End Function
```
您可以在Excel中创建一个新模块,并将此代码复制到模块中。然后,您可以在Excel中使用以下公式来调用此VBA函数:
```
=FindMax(A1:A10)
```
其中,A1:A10是您要查找最大值的单元格范围。您可以根据需要更改此范围。