最近两天在想用VBA写个宏处理点东西,对Excel的对象模型和方法不是很熟悉,写起来还真费劲,在这里备份一下,便于以后查找。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
Sub test_Click()
Dim nameRange As Range, tmpRange As Range
Dim findAddress As String
Dim finalRow As Integer
Set namedRange = Range("TestClick")
'The first method
Set tmpRange = namedRange.Find(What:="34534")
findAddress = tmpRange.Address
If Not tmpRange Is Nothing Then
Do
finalRow = tmpRange.Row
Set tmpRange = namedRange.FindNext(tmpRange)
'MsgBox tmpRange.Row
Loop While Not tmpRange Is Nothing And findAddress <> tmpRange.Address
End If
MsgBox finalRow
'the second Method
Set tmpRange = namedRange.Find(What:="345345", After:=namedRange.Cells(1), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
MsgBox tmpRange.Row
End Sub
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Sub test_Click()
Dim nameRange As Range, tmpRange As Range
Dim findAddress As String
Dim finalRow As Integer
Set namedRange = Range("TestClick")
'The first method
Set tmpRange = namedRange.Find(What:="34534")
findAddress = tmpRange.Address
If Not tmpRange Is Nothing Then
Do
finalRow = tmpRange.Row
Set tmpRange = namedRange.FindNext(tmpRange)
'MsgBox tmpRange.Row
Loop While Not tmpRange Is Nothing And findAddress <> tmpRange.Address
End If
MsgBox finalRow
'the second Method
Set tmpRange = namedRange.Find(What:="345345", After:=namedRange.Cells(1), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
MsgBox tmpRange.Row
End Sub