2017-01-13 27 views
1

我正在使用Excel 2016.我对应用程序的VBA有一定的经验,并且有一些编程经验。在Excel中读取条形码以查看是否匹配

我试图从条形码扫描仪获取输入信息,将其与电子表格中的列进行比较,如果有匹配项,则在某些单元格中放置几个​​字符和日期戳(缩写和日期,每个单独分隔列)。

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

这是非常令人沮丧,因为我认为这是一个简单的事情,已经解决了。与其努力解决问题和构建软件,似乎我在与语法和/或环境作斗争。我究竟做错了什么?

+0

'Match'返回行号(当它找到匹配项时),所以你不能像你那样设置我认为是'Range'的'matchedCell'。您是否想要从Range(“C2:C8”)中的哪个单元格中找到与您的“InputBox”匹配的单元格?然后将当前时间插入位于该单元格右侧2列的单元格中? –

+0

在第一行开始“matchedcell =”之前添加“Debug.print代码”,是您范围内的值吗?你也应该完全限定范围,即工作簿(“mybook.xlsx”)。sheets(“sheet1”)。range(“C2:C8”) – User632716

回答

2

两种可能性:

  • 使用功能对象

    和存储在一个变体可变其返回值的ApplicationMatch()到的任何错误进行检查(如果没有找到值)

    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 
    
  • 使用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 
    
+0

击败我,快速键盘:) –

+0

@ShaiRado,有时(太多次了),情况正好相反! – user3598756

+0

我无法让Match()工作,它一直返回错误2402,这可能是“#N/A”或找不到。代码的打印语句(现在重命名为scannedInput)是正确的,并且matchedCell给了我错误。我尝试将变量类型的matchedCell更改为double,但这没有帮助。您的第二个代码示例立即运行,无需修改,谢谢!希望我可以把我放在首位,现在我可以完成一些工作! – YetAnotherRandomUser

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 
相关问题