我正在制作一个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(描述)的值赋给标签
这应该有所帮助:
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
时没有发现任何东西,所以你可以使用这个小技巧以后如果我发布你以防万一你的BarCode尚未出现在你的数据库。
好的,最后修复了问题,不是我最初想的方式,但它完成了工作,我停止使用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