My vba code for a bunch of large ranges uses worksheetfunction.vlookup to find needed values. Ranges can be upwards of 25,000 cells, however, so this takes forever. Is there an equivalent function for arrays?
I've seen lots of SO answers that seem to address returning true/false in there is an exact string match. I need the string's location.
How about this ...
Function MyVLook(Arg As Range, Target As Range, ColIdx As Integer) As Range
Dim Idx As Integer
If Arg = "" Then
Set MyVLook = [ParamNothing]
Else
For Idx = 1 To Target.Rows.Count
If Target(Idx, 1) = Arg Then
If ColIdx < 0 Then
Set MyVLook = Target(Idx, 1).Offset(0, ColIdx)
Else
Set MyVLook = Target(Idx, ColIdx)
End If
Exit For
End If
Next Idx
End If
End Function
[ParamNothing] is a single cell range in a worksheet containing some application-specific text; otherwise this works almost like a normal VLOOKUP ... you can specify negative column offsets though (something I often miss in regular VLOOKUP), and I didn't built in a flag for range searches.
If you're only looking for the first occurrence try this:
Public Sub FindInRange()
Dim sValueToFind As String
Dim rRangeToSearch As Range
Dim rFoundRange As Range
sValueToFind = "The value I'm searching for"
With ThisWorkbook.Worksheets("Sheet1")
Set rRangeToSearch = .Range("A1:A1193")
Set rFoundRange = rRangeToSearch.Find( _
What:=sValueToFind, _
After:=rRangeToSearch.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not rFoundRange Is Nothing Then
MsgBox sValueToFind & " found in cell " & rFoundRange.Address & _
" and the value two cells to the right is " & rFoundRange.Offset(, 2), vbInformation + vbOKOnly
Else
MsgBox sValueToFind & " not found.", vbInformation + vbOKOnly
End If
End With
End Sub
This will find an exact match due to LookAt:=xlWhole and will not match the case due to MatchCase:=False. If you want to find the last occurrence use SearchDirection:=xlPrevious.
This mimics using Ctrl + F on the worksheet. For more info on VBA FIND see: https://msdn.microsoft.com/en-us/library/office/ff839746.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.