2017-01-13 28 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 
相關問題