ComboBox-Textbox Linked Values with VLOOKUP Function 只保留一定范围(不是所有范围)

ComboBox-Textbox Linked Values with VLOOKUP Function Only keep some certain range (Not all Range)

我有 1 个组合框 [Vendor_Number_CO_List] 和 1 个文本框 [Vendor_Name_Box_CO]。它们在excel、"B2:C15452"中都有自己的Cells值。我只想更改 ComboBox,而 TextBox 自动跟随指向单元格中的值。 我正在使用 VLOOKUP 函数,它是成功的,但仅在 "C9887" 下显示 TrueValue,如果它高于 C9887,则显示 FalseValue ... Textbox/Cells 范围内是否有任何限制?

我是 VBA 的新手,我昨天才开始做这件事..我非常喜欢它。我想做这样的事情,请大家帮忙解决这个问题。

我也尝试将范围缩短为:"B2:C9887",它只显示 FalseValue。 "C2:C9887" 和 "C9887:15452" 的唯一区别是它的单元格值。 "Number" 和 "Combination of word & Number"。

这是我的代码,

Private Sub Vendor_Number_CO_List_Change()

    Dim c, d As Variant


    c = Vendor_Number_CO_List.Value
    d = Application.VLookup(c, _
        ThisWorkbook.Sheets("Vendor Database").Range("B2:C15452"), 2, False)

    Vendor_Name_Box_CO.Value = IIf(IsError(d), "Vendor Not Found.", d)

End Sub

我想要当组合框指向 "B2:B15452" 中的值时它显示 excel 中的 "C2:C15452" 值。请各位大侠指点一下..

恭喜!看起来你的代码运行良好,除了你设计的错误条件。那行不通的。下面的代码展示了如何正确地实现你的想法。

    Private Sub Vendor_Number_CO_List_Change()

        Dim c As Variant, d As Variant
        Dim Rng As Range

        c = Vendor_Number_CO_List.Value
        Set Rng = Sheets("Vendor Database").Range("B2:C15452")

        On Error Resume Next
        d = Application.VLookup(c, Rng, 2, False)
        If Err.Number Then d = "Vendor Not Found"
'        If Len(d) = 0 Then d = "Vendor Not Found"

        Vendor_Name_Box_CO.Value = d
    End Sub

VLOOKUP 找不到部分单元格值。因此,在 "ABC-1234" 中找不到“1234”并不表示编码错误。您可以尝试实现以下逻辑。

  1. 如果没有找到没有前缀的条件,则会发生错误。
  2. 如有错误,请将前缀添加到c后重新搜索
  3. 仅当此操作也失败时才继续 "Value Not Found"。

您对变量的命名可能更加公正。 c 可能描述性不够,而 Vendor_Number_CO_List 可能描述性太强。如果您避免下划线和全部大写,您的代码将更具可读性。