Lookup Using Application.Match
- Using
Application.Match is easier and cleaner then using WorksheetFunction.Match because you can test the result with IsError or IsNumeric.
The Code
Option Explicit
Sub test()
' The cell containing the lookup value.
Dim cel1 As Range
Set cel1 = Sheet1.Range("B7")
' First 'available' cell in column `E` column, but in column `F`.
Dim cel4 As Range
Set cel4 = Sheet4.Range("E" & Sheet4.Rows.Count).End(xlUp).Offset(1, 1)
' Range from cell `A1` to the last non-empty cell.
Dim rng15 As Range
Set rng15 = Sheet15.Range("A1", Sheet15.Range("A" & Sheet15.Rows.Count).End(xlUp))
' The index of the found value. If not found, returns error value.
' Therefore we use 'Variant'.
Dim cMatch As Variant
cMatch = Application.Match(cel1.Value, rng15, 0)
' Test if found with 'IsNumeric()'. You can also use 'Not IsError()'
' instead. Or even 'IsError()', but then switch the statements.
If IsNumeric(cMatch) Then
cel4.Value = rng15.Cells(cMatch).Offset(, 1).Value
MsgBox "Value '" & cel1.Value & "' copied.", vbInformation, "Success"
Else
MsgBox "Value '" & cel1.Value & "' not found.", vbCritical, "Fail"
End If
End Sub
EDIT
- Adjust the sheets and cells appropriately.
Fill Range with Found Value
Sub test2()
' The cell containing the lookup value.
Dim cel1 As Range
Set cel1 = Sheet1.Range("B7")
' Range from cell 'E2' to the last non-empty cell, but column `F`.
Dim rng4 As Range
Set rng4 = Sheet4.Range("E2", Sheet4.Range("E" & Sheet4.Rows.Count) _
.End(xlUp)).Offset(, 1)
' Range from cell `A1` to the last non-empty cell.
Dim rng15 As Range
Set rng15 = Sheet15.Range("A1", Sheet15.Range("A" & Sheet15.Rows.Count) _
.End(xlUp))
' The index of the found value. If not found, returns error value.
' Therefore we use 'Variant'.
Dim cMatch As Variant
cMatch = Application.Match(cel1.Value, rng15, 0)
' Test if found with 'IsNumeric()'. You can also use 'Not IsError()'
' instead. Or even 'IsError()', but then switch the statements.
If IsNumeric(cMatch) Then
rng4.Value = rng15.Cells(cMatch).Offset(, 1).Value
MsgBox "Value '" & cel1.Value & "' copied.", vbInformation, "Success"
Else
MsgBox "Value '" & cel1.Value & "' not found.", vbCritical, "Fail"
End If
End Sub
Sheet15.Range("A" & whatever).Offset(, 1)to a range (an array)Sheet4.Range("F11:F" & lastR4).Value. Think about it for a while and then clarify what you want to write where.B7ofSheet1in columnAofSheet15. If it is not found, do nothing (or return a message box). If it is found, write the value of the cell next to the cell of the found value to the next available cell in columnFofSheet4. Best do it in your post.