我尝试使用下面的代码在某个范围内查找字符串,但出现错误:“未设置对象变量或 With 块变量。”它看起来很简单,但我找不到我的错误。
Sub FindSomethingInRange()
Dim sSearchFor as String
Dim rSearchRange as Range
sSearchFor = Worksheets("MatchupCalc").Range("E" & i2).Value
Set rSearchRange = ThisWorkbook.Sheets("Ladder").Range("AP38:AX38")
Debug.Print FindValueInCellRange(rSearchRange, sSearchFor)
End Sub
Function FindValueInCellRange(MyRange As Range, MyValue As Variant) As String
'---> PURPOSE: Returns address of first cell in range where the value is found.
With MyRange
FindValueInCellRange = .Find(What:=MyValue, After:=.Cells(.Cells.Count),
LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows,
SearchDirection:=xlNext).Address(RowAbsolute:=False, ColumnAbsolute:=False)
End With
End Function
你说的
After:=.Cells(.Cells.Count)
是什么意思? 另外,如果什么也没找到,你应该检查会发生什么。
Function FindValueInCellRange(MyRange As Range, MyValue As Variant) As String
'---> PURPOSE: Returns address of first cell in range where the value is found.
Dim FoundCell As Range
With MyRange
Set FoundCell = .Find(What:=MyValue, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
' Check if the value was found
If Not FoundCell Is Nothing Then
FindValueInCellRange = FoundCell.Address(RowAbsolute:=False, ColumnAbsolute:=False)
Else
FindValueInCellRange = "Not Found"
End If
End With
End Function