在excel中读取条形码以查看是否存在匹配

时间:2017-01-13 15:30:19

标签: excel vba excel-vba

我正在使用Excel 2016.我对应用程序的VBA有一定的经验,并且有一些编程经验。

我正在尝试从条形码扫描仪获取输入,将其与电子表格中的列进行比较,如果匹配,则在一些单元格中放置一些字符和日期戳(缩写和日期,每个都在单独的列中) )。

This question具有非常相似的用例,并包含代码示例。我已经尝试过代码示例,无法让它工作。起初,阵列存在问题。最终我发现你可以做“C2:C8”,这似乎有效,虽然没有在任何地方记录(可能是基础课程/课程的一部分,但是找不到)。有关Match()定义的子或函数的错误,因此我在Solver中启用了security center加载项。这没有解决它,所以我发现这个forum post解释了Match不是VBA函数。

现在,单击“运行时错误1004,无法获取WorksheetFunction类的Match属性”按钮后出现错误,单击调试将我带到同一行。

以下是我结束的代码:

Private Sub CommandButton1_Click()

code = InputBox("Please scan a barcode and hit enter if you need to")
matchedCell = Application.WorksheetFunction.Match(code, Range("C2:C8"), 0)
matchedCell.Offset(0, 2) = Now

End Sub

这令人非常沮丧,因为我觉得这很简单,已经解决了。而不是努力解决问题和构建软件,似乎我正在与语法和/或环境作斗争。我做错了什么?

2 个答案:

答案 0 :(得分:2)

两种可能性:

  • 使用Application对象

    Private Sub CommandButton1_Click() Dim code As Variant Dim matchedCell As Variant code = InputBox("Please scan a barcode and hit enter if you need to") matchedCell = Application.Match(code, Range("C2:C8"), 0) If Not IsError(matchedCell) Then Range("C2:C8").Cells(matchedCell, 1).Offset(0, 2).Value = Now End Sub 函数

    并将其返回值存储在Variant变量中,以检查是否存在任何错误(如果未找到值)

    Find()
  • 使用Range对象

    Private Sub CommandButton1_Click() Dim code As Variant Dim matchedCell As Range code = InputBox("Please scan a barcode and hit enter if you need to") Set matchedCell = Range("C2:C8").Find(what:=code, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=True) If Not matchedCell Is Nothing Then matchedCell.Offset(0, 2).Value = Now End Sub 函数
    continue

答案 1 :(得分:0)

使用Application.Match,并仅在成功Match时继续运行代码。

Option Explicit

Private Sub CommandButton1_Click()

Dim MatchRow As Variant
Dim code As Variant
Dim matchedCell As Range

code = InputBox("Please scan a barcode and hit enter if you need to")

' verify that there is a successful match in the searched range
If Not IsError(Application.Match(code, Range("C2:C8"), 0)) Then
    MatchRow = Application.Match(code, Range("C2:C8"), 0) '<-- get the row number 
    Set matchedCell = Range("C" & MatchRow + 1) '<-- set the range (add 1 row since you are starting from row 2)
    matchedCell.Offset(0, 2).Value = Now

    'option 2: without setting the range
    Range("C" & MatchRow).Offset(1, 2).Value = Now  
End If

End Sub