关于textbox1&中给出的值的Vlookup textbox2&从sheet2返回另一个testbox3中的值

时间:2016-11-03 19:04:15

标签: excel-vba vlookup vba excel

我需要有关vlookup的excel vba代码的帮助,其中包含来自textbox 1和amp;的2个值。文本框2。

  1. 我在Thisworkbook中有一个名为lookup(动态表)Image Sheet with lookup data
  2. 的工作表

    我有一个包含3个文本框的用户表单,用户将在其中提供文本框1&如果在查找列中找到textbox2值,则textbox3必须从上表中的col c返回vlookup值 Image of Userform

    他查找表行是动态的但是列是固定的所以我编写了以下代码来获取范围,textbox1& textbox2值然后将其传递给函数以获取文本框3中的值

    但代码不起作用,我也不明白如何将2个条件从textbox传递到vlookup&在第3个框中返回值

    代码

    Private Sub CommandButton1_Click()
    
    Dim wb As Workbook
    Dim sht As Worksheet
    Dim userange As Range
    Dim lastrow As Long
    Dim lastcolumn As Long
    Dim startcell As Range
    
    'Finding the dynamic table range in sheet lookup
    
    Set sht = ThisWorkbook.Worksheets("lookup")
    Set startcell = Range("A1")
    
    'Find Last Row and Column
        lastrow = sht.Cells(sht.Rows.Count, startcell.Column).End(xlUp).Row
        lastcolumn = sht.Cells(startcell.Row,                sht.Columns.Count).End(xlToLeft).Column
    
    'select range
       userange = sht.Range(startcell, sht.Cells(lastrow, lastcolumn)).Select
    
    'Constraints from 2 textboxs given in userform
    Dim cit1 As String
    cit1 = TextBox1.Value 'textbox1
    Dim cit2 As String
    cit2 = TextBox2.Value 'textbox2
    
    'calling vlookup function by passing the lookup range from above, return        value in col D if col B in excel sheet(lookup) has textbox 1.value & col C in excel sheet(lookup) has textbox2.value
    
    Two_Con_Vlookup(userange,D,cit1,cit2)
    End Sub
    
    Function Two_Con_Vlookup(Table_Range As Range, Return_Col As Long, Col1_Fnd, Col2_Fnd)
    
    Dim rCheck As Range, bFound As Boolean, lLoop As Long
    On Error Resume Next
    
    Set rCheck = Table_Range.Columns(1).Cells(1, 1)
    
    With WorksheetFunction
    
        For lLoop = 1 To .CountIf(Table_Range.Columns(1), Col1_Fnd)
    
           Set rCheck = Table_Range.Columns(1).find(Col1_Fnd, rCheck, xlValues, xlWhole, xlNext, xlRows, False)
    
           If UCase(rCheck(1, 2)) = UCase(Col2_Fnd) Then
    
                bFound = True
    
                Exit For
    
            End If
    
        Next lLoop
    
    End With
    
    If bFound = True Then
    
        Two_Con_Vlookup = rCheck(1, Return_Col)
        'textbox3 must return with col D
        TextBox3 = Two_Con_Vlookup.Value
    
    Else
    
     Two_Con_Vlookup = "#N/A"
      TextBox3 = Two_Con_Vlookup.Value
    
    End If
    

    结束功能

1 个答案:

答案 0 :(得分:1)

这可能不是最佳解决方案,但它会为您提供所需的结果。

在“查找”表格中创建一个辅助列,连接A列和B列。

然后使用Textbox1和Textbox2的串联进行查找。