可以通过 和 的组合来Worksheet_Change
实现Vlookup
。请将此代码放在工作表代码部分。
一旦在A1
宏中输入值,就会触发,如果在表中找到值,它会使用 Vlookup 获取相应的值(描述)。它还输入当前日期和时间。
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Application.EnableEvents = False
If Not Intersect(Target, Range("A1")) Is Nothing Then
Dim lastRow As Long, tblRng As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
If lastRow <= 3 Then lastRow = 3
Set tblRng = Range("A3:D" & lastRow)
dt = Application.VLookup(Target, tblRng, 1, 0)
If Not IsError(dt) Then
With Target
.Offset(0, 1).Value = Application.VLookup(Target, tblRng, 2, 0)
.Offset(0, 2).Value = Date
.Offset(0, 2).NumberFormat = "mm/dd/yyyy"
' if you want date from tbl use Application.VLookup(Target, tblRng, 3, 0)
.Offset(0, 3).Value = TimeValue(Now())
.Offset(0, 3).NumberFormat = "hh:mm am/pm"
' if you want date from tbl use Application.VLookup(Target, tblRng, 4, 0)
End With
Else
With Target
.Offset(0, 1).Value = vbNullString
.Offset(0, 2).Value = vbNullString
.Offset(0, 3).Value = vbNullString
End With
End If
End If
Application.EnableEvents = True
End Sub