我假设您的条形码阅读器已“连接”到您的键盘电缆中,并且 - 可以这么说 - 将击键发送到您的 PC。因此,只要您的 Excel 光标位于工作表的第 5 列(第二个退出条件),VBA 代码就会在光标右侧的单元格 1 和 2(即 F..G 列)中添加日期和时间每次拍摄。
如果您想将日期和时间放置在工作表的第二和第三列(即 B..C 列)中,而不管您的光标在 Worksheet_Change 触发器触发时的位置,您都应该使用此代码
Target.EntireRow.Cells(1, 2).Value = Date
Target.EntireRow.Cells(1, 3).Value = Time
现在...在另一个 Excel 表格中查找捕获的条形码并找到匹配的序列号可以像 VLOOKUP 功能一样简单,您可以自动粘贴到日期旁边的单元格中,或者您可以使用 Do ... While 。 .. 循环构造扫描(命名)范围:
....
Target(1, 4) = SernoByBarcode(Target)
....
和
Private Function SernoByBarcode(Barcode As String) As String
Dim DBase As Range, Idx As Long
Set DBase = Range("Database") ' named range "Database" contains Barcode in column1, SerNo in column2
Idx = 2 'first row contains headers
SernoByBarcode = "#NOT/FOUND" ' default return value
Do While DBase(Idx, 1) <> "" ' break on 1st empty record
If DBase(Idx, 1) = Barcode Then
SernoByBarcode = DBase(Idx, 2)
Exit Function
End If
Idx = Idx + 1
Loop
End Function
如果您在设置日期和时间之前调用 Function SernoByBarcode,您可以使用另外一条 IF 语句来确定输出格式(即包括/不包括序列号)
编辑
始终在同一个单元格中扫描条形码(我选择 B2)扫描列表从第 5 列开始是否存在条形码...如果是,则写入 8/9/10 否则 5/6/7 ...查找功能只能用于稍加修改,现在返回行索引而不是字符串值
Private Sub Worksheet_Change(ByVal Target As Range)
' Barcode always scanned into cell B2
' if barcode found in column 5, fill column 8,9,10 else fill columns 5,6,7
' row 1, columns 5..10 contain column headers
Dim Idx As Long
If Target.Row = 2 And Target.Column = 2 Then
Application.EnableEvents = False
Idx = FindBarcode(Target.Value)
If Me.Cells(Idx, 5) = "" Then
Me.Cells(Idx, 5) = Target.Value
Me.Cells(Idx, 6) = Date
Me.Cells(Idx, 7) = Time
Else
Me.Cells(Idx, 8) = Target.Value
Me.Cells(Idx, 9) = Date
Me.Cells(Idx, 10) = Time
End If
' keep cursor in Scan field
Me.Cells(2, 2).Select
Application.EnableEvents = True
End If
End Sub
Private Function FindBarcode(Barcode As String) As Long
Dim DBase As Range, Idx As Long
Set DBase = ActiveSheet.[E1] ' start of table
Idx = 2 'first row contains headers
Do While DBase(Idx, 1) <> "" ' break on 1st empty record
If DBase(Idx, 1) = Barcode Then
Exit Do
End If
Idx = Idx + 1
Loop
FindBarcode = Idx
End Function