VBA Excel 的宏仅读取条码的一部分

VBA macro for Excel to only read Part of a barcode

我在 Excel 中使用以下 VBA 代码从条形码扫描仪读取输入并在现有列 (C) 中搜索匹配值。我正在扫描的条形码末尾有一些 "extra" 个字符(在 space 之后),我不想扫描这些字符,或者至少不想针对 C 列中的值搜索这些字符。是否有我可以让条形码 reader 忽略 space 之后的字符或将扫描限制为前 X 个字符等的方法?

Sub DataInput()
    Dim SearchTarget As String
    Dim myRow As Long
    Dim Rng As Range
    Static PrevCell As Range
    Dim FoundCell As Range
    Dim CurCell As Range


10  'SearchTarget = "qwer"
    SearchTarget = InputBox("Scan or type product barcode...", "Scan Barcode")

    If SearchTarget = "" Then GoTo 30

    If PrevCell Is Nothing Then
        myRow = Selection.Row
        Set PrevCell = Range("C" & myRow)
    End If


    Set Rng = Range("C:C,C:C") 'Columns for search defined here
    With Rng
        Set FoundCell = .Cells.Find(What:=SearchTarget, _
        After:=PrevCell, LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
        MatchCase:=False)
    End With

    If FoundCell Is Nothing Then
        MsgBox "These are not the Droids you are looking for"

    Else
        FoundCell.Activate
        '        If PrevCell.Address = FoundCell.Address Then
        '            MsgBox "found a match!"
        '        End If
        ActiveCell.Offset(0, 1).Select
        timestamp = Format(Now(), "dd-mmm-yy hh:mm")
        ActiveCell = timestamp
        ActiveCell = Now()

        MsgBox "FOUND IT!!  SEND TO LES"
        ' Found.Show
        If Found.CommandButton1 Then GoTo 20

        Set PrevCell = FoundCell
    End If
20  GoTo 10


30  End Sub

使用 left() 命令仅使用字符串的前 x 个字符。类似于:

TrimmedBarcode = left(UntrimmedBarcode, x)

TrimmedBarcode 是您存储缩短的条形码的位置,UntrimmedBarcode 是扫描仪的输入,x 是您需要的字符数。

编辑:使用您的变量,

SearchTarget = Left(InputBox("Scan or type product barcode...", "Scan Barcode"), 6)

将 6 调整为您需要的任意字符数。

您可以使用 Split 函数 --- 它会在您指定的字符上拆分一个字符串,return 一个包含拆分字符串的数组。例如

SplitString = Split(MyString, " ")

将在出现 space 的任何地方拆分字符串。如果你想要第一个 space 之前的所有内容,你可以使用这个

LeftOfFirstSpace = Split(Barcode, " ")(0)

您还可以使用 InStr 函数在字符串中进行搜索。

希望对您有所帮助。

感谢您的帮助!我发现这两种方法都可行,但我的应用程序决定使用 Left 函数,因为在我的应用程序中已确定,条形码的前 8 个字符应始终是我要搜索的值。