So I need a UDF that is able to find values to the left and right of a found value and able to find the nth match of a value for a quality monitoring sheet I am making. This is what I have right now and I was wondering if there are any critiques or tips/tricks to make it more efficient (it is, however, already MUCH faster than using array functions).
The UDF must return a value error if nothing is found.
Public Function bestVLookup(varLookupval As Variant, rngLookup As Range, intColIndex As Integer, intColOffset As Integer, intValIndex As Integer)
'declarations
' varLookupval is the value to be looked up. declared as variant.
' rngLookup is the range we are looking in. the value to be looked up and the value to be returned MUST be in this range
' intColOffset is the column offset from the found value to find the return value in. can be negative to go right or positive to go left. can not be 0
' intValIndex is the parameter which tells us which match to return. returns the intValIndex'th search result. must be 1 or greater
' intColIndex is an parameter if we know the column in the rngLookup that the varLookupval is in.
If (intValIndex > 1) Then
Dim valCount As Integer
valCount = 0 ' counter to skip matches until the intValIndex'th value
For rowCount = 1 To rngLookup.Rows.Count
If rngLookup.Cells(rowCount, intColIndex) = varLookupval Then
valCount = valCount + 1
If valCount = intValIndex Then
bestVLookup = rngLookup.Cells(rowCount, intColIndex).Offset(0, intColOffset).Value
Exit Function
End If
End If
Next
bestVLookup = CVErr(xlErrValue)
ElseIf (intValIndex = 1) Then
For rowCount = 1 To rngLookup.Rows.Count
If rngLookup.Cells(rowCount, intColIndex) = varLookupval Then
bestVLookup = rngLookup.Cells(rowCount, intColIndex).Offset(0, intColOffset).Value
Exit Function
End If
Next
bestVLookup = CVErr(xlErrValue)
Else
bestVLookup = CVErr(xlErrValue)
End If
End Function
I'm somewhat of a novice at UDFs and macros so any tips/tricks would be super appreciated.
Thank you very much in advance,
Andrew Harris
Bookmarks