我正在使用条形码阅读器在1个单元格中输入序列号,然后使用以下内容在下两个单元格中自动添加日期和时间:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 5 Then Exit Sub
If Target.Column <> 5 Then Exit Sub
Application.EnableEvents = False
Target(1, 2).Value = Date
Target(1, 3).Value = Time
Application.EnableEvents = True
End Sub
我希望能够扫描条形码并自动查找序列号并在两个“其他单元4&amp; 5”中放置日期时间戳,或者如果该序列号不在单元格中,则将其放在那里并放入日期时间在2&amp; 3个细胞。
答案 0 :(得分:0)
我认为您的条形码阅读器是“tee-ed”到您的键盘电缆中 - 也就是说 - 将键击发送到您的PC。因此,只要您的Excel光标位于工作表的第5列(第2个退出条件),VBA代码就会在单元格1和1中添加日期和时间。每次拍摄后2光标右侧(即F..G列)。
如果要将日期和时间定位到工作表的第2和第3列(即列B..C),而不管在Worksheet_Change触发器触发时光标的位置,则应使用此代码< / p>
Target.EntireRow.Cells(1, 2).Value = Date
Target.EntireRow.Cells(1, 3).Value = Time
现在......在另一个Excel表中查找捕获的条形码并查找匹配的序列号可以像VLOOKUP函数一样简单,您可以自动粘贴到日期旁边的单元格中,或者您可以使用Do .. 。While ... Loop构造来扫描(命名)范围:
....
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