Vlookup上出现“下标超出范围”错误

时间:2019-04-08 09:39:53

标签: excel vba

我正在制作一个vlookup代码,当他们扫描项目条形码时显示用户描述,但是下标超出范围错误

 Dim ws As Worksheet
 Set ws = Sheets("CONVERSION")



 Dim itemcode As String
 Dim description As String
 Dim myrange As Range
 ws.Activate
Set myrange = Range("A:B")
description = ws.Application.WorksheetFunction.VLookup(TextBox1.Value, Worksheets("CONVERSION").Range("myrange"), 2, False)
 Label5 = description

然后应该将vlookup(描述)的值分配给标签

2 个答案:

答案 0 :(得分:2)

这应该有帮助:

Option Explicit
Sub Test()

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("CONVERSION") 'if you don't define the workbook it will be the activeworkbook
    Dim itemcode As String
    Dim description As Variant 'Defining it as variant won't rise an Error if the item is not found
    Dim myrange As Range

    Set myrange = ws.Range("A:B") 'If you define a worksheet, you can refer to it and you won't need .Select or .Activate
    description = Application.VLookup(TextBox1.Value, myrange, 2, False) 'as before, once you defined your range you can simply refer to it

    If Not IsError(description) Then
        Label5 = description
    Else 'if nothing is found description will be an error
        Label5 = "Item not found"
    End If


End Sub

Application.VLookUp而不是使用WorksheetFunction可以防止VBA在将其应用于Variant时没有发现任何错误的情况下出现错误,因此您可以使用该小技巧稍后进行if如果您的条形码尚未出现在数据库中,我已经将您发布了。

答案 1 :(得分:0)

Ok Finaly解决了问题,不是我最初的想法,但它完成了工作,我停止使用vlookup并做到了

    Dim Found As Range
Dim str As String

str = Me.TextBox1.Text
Set Found = Sheet2.Range("A2", Range("A" & Rows.Count).End(xlUp)).Find(str)

    If Found Is Nothing Then
      Label5 = "Not Found"
    Else
      Label5 = Cells(Found.Row, 2).Value

    End If

我找到了解决方法here