使 Excel 查找宏灵活覆盖不同的参考长度

Making an Excel lookup marco flexible to cover different reference lengths

我有一个宏,它正在搜索 3 个作品sheet 来寻找用户可能输入的 invoice number(总共超过 260 万条记录)。

数字出现在一个单元格中,其中也有一个查找引用。形式:invoicenumber, reference_letter

本来没问题,因为 invoice numbers 是 10 位数字。现在它们可以是任何东西,但最后总是有一个逗号,在单个字符引用之前。

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address <> "$A" Then Exit Sub
If Target.Value = "" Then Exit Sub

Application.EnableEvents = False

Range("B5") = ""

For Each sh In Sheets
    If sh.Name = ActiveSheet.Name Then GoTo 111
    sh.Range("B1").FormulaArray = "=IFERROR(MATCH(Main!A5,LEFT(A:A,10),0),"""")"
    If sh.Range("B1") <> "" Then
        x = sh.Range("B1")
        Range("B5") = Right(sh.Range("A" & x), 1)
        Exit For
    End If
111
Next sh

Application.EnableEvents = True

If x = "" Then MsgBox "Not Found!"

End Sub

我知道这个 10 个字符的限制在第 8 行,我尝试用 FIND 替换,但我认为我做错了(因为我无法得到它上班!)。

如果能帮助我解决这个问题,我将不胜感激。

我还有一个 vLookup,它获取最后一个字符并从单独的 sheet 返回文本。

试试这个

Private Sub Worksheet_Change(ByVal Target As Range)
Dim InvLen As Integer
If Target.Address <> "$A" Then Exit Sub
If Target.Value = "" Then Exit Sub
Application.EnableEvents = False
Range("B5") = ""
    For Each sh In Sheets
        If sh.Name = ActiveSheet.Name Then GoTo 111
        InvLen = Len(Worksheets("Main").Range("A5").value)
        sh.Range("B1").FormulaArray = "=IFERROR(MATCH(Main!A5,LEFT(A:A," & InvLen & "),0),"""")"
        If sh.Range("B1") <> "" Then
            x = sh.Range("B1")
            Range("B5") = Right(sh.Range("A" & x), 1)
            Exit For
        End If
111
    Next sh
Application.EnableEvents = True
If x = "" Then MsgBox "Not Found!"
End Sub