尽管类型和值相等,Vlookup VBA 中出现错误 2042



Summerization:尽管两个字符串看起来相等,但它们与各自单元格中的文本不匹配。即使第三个确实与它匹配。

我被赋予了"如果可能"的任务,以简化在复杂的 excel 工作簿中的导航。我想出了一种更好的方法来生成 ID,因为旧的几乎是荒谬的。

我的 ID 是由 3 个不同的数字创建的,我正在制作的宏通过描述来反转这些 ID,并解释 ID 代表什么。

示例:550000210前五个代表帐户,后面两个代表目的,后两个代表分配(方法(。所有 3 个 ID 的格式都相同(或者我认为是这样(,它们都是字符串(文本(。最终的 ID 也是一个字符串(文本(。

然而,令我惊讶的是,在 VBA 中使用 VLookup 函数并不容易,除了前 5 位数字之外,这两对也与它们所引用范围内的值不匹配。

这让我认为"legenda"表中的命名范围不共享格式,因为帐号是由在线系统生成的,但对是由我生成的。所以我删除了格式并复制了帐号的格式,它没有改变任何东西,尝试了双倍而不是帮助。 使用添加手表,它说我希望它找到的数字是相同类型的"变体/字符串",当我在比较它们时,它成功通过。

我真的越来越绝望了,我不一定有时间压力,但这应该是"尝试"尝试的一小步,看看它是否适用于这项任务。

Let sel = Selection.Value 'user selects the code they want (vbModeless)
Let a = Left(sel, 5) 'first 5 digits
Let b = Mid(sel, 6, 2) 'the two after
Let c = Right(sel, 2) 'left two digits
Label1.Caption = a
Label2.Caption = b
Label3.Caption = c
Dim sourceSheet As Worksheet
Dim targetWorkbook As Workbook
Set targetWorkbook = Application.ActiveWorkbook
Set legendaSheet = targetWorkbook.Worksheets("legenda")
Dim ra As Range, rb As Range, rc As Range
Set ra = legendaSheet.Range("account")
Set rb = legendaSheet.Range("purpose")
Set rc = legendaSheet.Range("distribution")
'changes single digit back to single digit (needed)
'code does not work even when this condition isn't needed (aka numbers 10 or higher)
If Left(b, 1) = "0" Then
b = Replace(b, "0", "")
End If
If Left(c, 1) = "0" Then
c = Replace(c, "0", "")
End If

Let e = Application.VLookup(a, ra, 2, False) 'works here
Let f = Application.VLookup(b, rb, 1, False) 'error 2042
Let g = Application.VLookup(c, rc, 1, False) 'error 2042
Label4.Caption = e
Label5.Caption = f
Label6.Caption = g

预期结果是将 ID 部分放在标签的左列中,在右列中包含描述。它仅适用于"a"。但是,我怀疑问题实际上仍在格式化。

当 VLOOKUP 找不到该值时,将返回错误 2042。如果在公式中使用 VLOOKUP(输入到单元格中(,则为 #N/A。

首先,确保数据类型匹配。变量 a、b 和 c 的类型为 String,用于存储文本数据。rb 和 rc 很可能包含数字而不是文本。所以你必须将b(和c(转换为数值:

Let f = Application.VLookup(CLng(b), rb, 1, False) 'error 2042

其次,您应该为找不到值的情况准备代码:

Let f = "not found"
On Error Resume Next
f = Application.VLookup(CLng(b), rb, 1, False) 'error 2042
On Error Goto 0
' If found, f is the value from the sheet, otherwise "not found"

或者,您可以将工作表上的数据转换为正确的类型。

更新

好的,所以问题是你想在目的的第二列中搜索。为此,您必须调整该 rb:

Set rb = legendaSheet.Range("purpose").Offset(0, 1)

如果要从找到的行返回的列在搜索的列之前,则必须使用 INDEX 和 MATCH 函数。

最新更新