首页 > 解决方案 > 在另一个工作表中查找

问题描述

我目前正在开发用户表单。在这个用户窗体中,数据输入到 textbox4 中,数据通过基于 Vlookup 的 commandbutton3 放置到 textbox6 中。但是,vlookup 必须从 A:B 范围内的工作表“DB - verzamelformulier”中检索其数据。目前我收到错误消息:需要 424 个对象。有人可以帮我写代码吗?

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("DB - verzamelformulier")

With ws
Texbox6.Formula = "VLookup(TextBox4.Value, DB - verzamelformulier!$A:$B), 2, False)"

End With
End Sub

标签: excelvbavlookup

解决方案


有趣的方法,但您不能将公式分配给文本框,只能分配给单元格。试试这样的功能:

Function VerzamelFormulier(LookUpValue As Variant) As Variant
    Dim WS As Worksheet
    Dim R As Range

    Set WS = ThisWorkbook.Worksheets("DB - verzamelformulier")
    Set R = WS.Range("A:A").Find(LookUpValue, LookIn:=xlValues, Lookat:=xlWhole)
    If R Is Nothing Then
        ' The value wasn't found.
    Else
        ' Return the value from the cell in the same row and column B.
        VerzamelFormulier = WS.Cells(R.Row, 2)
    End If
End Function

在 TextBox4 的更改事件上调用它,以便每当它更改时,TextBox6 的值都会更新。

Private Sub TextBox4_Change()
    TextBox6.Value = VerzamelFormulier(TextBox4.Value)
End Sub

推荐阅读