VBA 查找 ( For Each...Next
, Application.Match
)
Option Explicit
Sub CustomersLookup()
' Source
Const sName As String = "Database" ' Worksheet Name
Const sfRow As Long = 2 ' First Data Row
Const slCol As String = "C" ' Lookup Column
Const svCol As String = "H" ' Value Column
' Destination
Const dName As String = "Tool" ' Worksheet Name
Const dfRow As Long = 2 ' First Data Row
Const dlCol As String = "A" ' Lookup Column
Const dvCol As String = "B" ' Value Column
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Source
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim slRow As Long: slRow = sws.Cells(sws.Rows.Count, slCol).End(xlUp).Row
If slRow < sfRow Then Exit Sub
Dim slrg As Range ' Source Lookup Range (Lookup Range)
Set slrg = sws.Range(sws.Cells(sfRow, slCol), sws.Cells(slRow, slCol))
Dim svrg As Range ' Source Value Range
Set svrg = slrg.EntireRow.Columns(svCol)
' Destination
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim dlRow As Long: dlRow = dws.Cells(dws.Rows.Count, dlCol).End(xlUp).Row
If dlRow < dfRow Then Exit Sub
Dim dlrg As Range ' Destination Lookup Range
Set dlrg = dws.Range(dws.Cells(dfRow, dlCol), dws.Cells(dlRow, dlCol))
' Destination Value Range is handled per cell, using 'EntireRow'.
Application.ScreenUpdating = False
' Loop and write.
Dim dlCell As Range ' Destination Lookup Cell (Lookup Value)
Dim dvCell As Range ' Destination Value Cell (Result)
Dim srIndex As Variant ' Source Row Index (Row of the Match)
Dim dString As String ' Lookup Value Converted to a String
For Each dlCell In dlrg.Cells
If Not IsError(dlCell) Then ' check if error value
dString = CStr(dlCell.Value)
If Len(dString) > 0 Then ' check if blank
Set dvCell = dlCell.EntireRow.Columns(dvCol)
' Attempt to find a match.
srIndex = Application.Match(dString, slrg, 0)
If IsNumeric(srIndex) Then ' match found
dvCell.Value = svrg.Cells(srIndex).Value
Else ' match not found
dvCell.Value = "Nope" ' or whatever
End If
End If
End If
Next dlCell
Application.ScreenUpdating = True
MsgBox "Operation finished successfully.", vbInformation, "Customers Lookup"
End Sub