在Excel中读取条码,看看是否有匹配

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

我正在尝试从条形码扫描器获取input信息,将其与电子表格中的列进行比较,如果匹配,请在某些单元格中input几个字符和date戳(缩写和date,每个单独列)。

这个问题有一个非常相似的用例,并包含一个代码示例。 我已经尝试了代码示例,无法使其工作。 起初,arrays有问题。 最终我想到你可以做“C2:C8”,这似乎工作,虽然这没有logging在任何地方(可能是基础课程/类的一部分,但无法find)。 对于Match()定义的子或函数有一个错误,所以我启用了安全中心的Solver加载项。 这并没有解决它,所以我发现这个论坛post解释了匹配不是一个VBA函数。

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

这里是我已经结束的代码:

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 

这是令人难以置信的挫折,因为我认为这是一个简单的事情,已经解决了。 我不是在努力解决问题和构build软件,而是在与语法和/或环境作斗争。 我究竟做错了什么?

两种可能性:

  • 使用Application对象的Match()函数

    并将其返回的值存储在Variantvariables中,以检查是否有任何错误(如果未find值)

     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 
  • 使用Range对象的Find()函数

     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 

使用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