在对Excel数据进行分析时,有时需要找到该区域中数据的最大值,使用VBA中的Find方法能够方便地实现这一操作。本文介绍查找并定位单元格区域中的最大值的方法。
1、启动Excel并打开Visual Basic编辑器,在工程资源管理器中插入一个模块,在模块的“代码”窗口中输入程序代码,如图1所示。具体的程序代码如下所示:
Sub GetMaxs()
Dim aRange As Range
Dim aMaxVal As Double
If TypeName(Selection)<>"Range "Then
Exit Sub '如果没有选中区域,则退出程序
End If
If Selection.Count=1 Then
Set aRange=Cells '如果仅选中一个单元格,则搜索整个工作表
Else
Set aRange=Selection
End If
aMaxVal=Application.Max(aRange) '获取区域中的最大值
On Error Resume Next
aRange.Find(aMaxVal,aRange.Range("A1"),xlValues,xlWhole,xlByRows,xlNext,False).Select
If Err<>0 Then
MsgBox"没有找到最大值:"&aMaxVal
End If
End Sub