当我单击每个查找值的选项按钮时,使用来自不同工作表的vlookup函数的userform

时间:2018-01-26 16:30:02

标签: excel vba combobox vlookup radio-button

我必须知道,这可能是单个组合框通过使用选项按钮从2张不同的表中列出的。这很好用。但是vlookup功能仅适用于工作表1而不适用于工作表2。 解释:
在我的用户表格中,
1个组合框= cmbbx1
2个选项按钮= 1.hq 2.whs
2个文本框= 1.txtbx1 2.txtbx2

当我点击选项按钮hq时,sheet1列表会显示在组合框中。然后另外2个文本框已经用Application.WorksheetFunction.Vlookup编码,所以它们显示给定的单元格值。

但是当我点击选项按钮whs时,我无法使其正常工作。在这个时候,组合框显示了sheet2中的列表,但是vlookup在这里没有工作。

这是我从另一个vlookup函数源获取的代码。

Private Sub CmbBX1_AfterUpdate()
    'Check to see if value exists
    If WorksheetFunction.CountIf(Sheet2.Range("B:B"), Me.CmbBX1.Value) = 0 Then
        MsgBox "Employee Not Registered"
        Me.CmbBX1.Value = ""
        Exit Sub
    End If
    'Lookup values based on control
    With Me
        .TxBx1 = Application.WorksheetFunction.VLookup(Me.CmbBX1, Sheet2.Range("Emp_ltl"), 2, 0)
        .TxBx2 = Application.WorksheetFunction.VLookup(Me.CmbBX1, Sheet2.Range("Emp_ltl"), 3, 0)
    End With
End Sub

这是我用于选项按钮的代码:

Option Explicit

Public myList As Variant
Private Sub hq_Click()
myList = ThisWorkbook.Worksheets("LTL").Range("Emp_ltl").Value
Me.CmbBX1.List = myList
End Sub

Private Sub whs_Click()
myList = ThisWorkbook.Worksheets("LTS").Range("Emp_ltS").Value
Me.CmbBX1.List = myList
End Sub

1 个答案:

答案 0 :(得分:0)

我相信以下内容会做到这一点:

Private Sub CmbBX1_AfterUpdate()
    If hq.Value = True Then 'check if hq is selected
        Dim ws As Worksheets: Set ws = Worksheets("LTL") 'declare your worksheet and your range
        Dim rng As Range: Set rng = ws.Range("Emp_ltl")
        myList = ThisWorkbook.Worksheets("LTL").Range("Emp_ltl").Value
        Me.CmbBX1.List = myList
    ElseIf whs.Value = True Then 'if whs is selected
        Dim ws As Worksheets: Set ws = Worksheets("LTS") 'declare and set your worksheet and range
        Dim rng As Range: Set rng = ws.Range("Emp_ltS")
        myList = ThisWorkbook.Worksheets("LTS").Range("Emp_ltS").Value
        Me.CmbBX1.List = myLis
    Else
        MsgBox "No Option has been selected"
        Exit Sub
    End If
    'Check to see if value exists
    If WorksheetFunction.CountIf(ws.Range("B:B"), Me.CmbBX1.Value) = 0 Then
        MsgBox "Employee Not Registered"
        Me.CmbBX1.Value = ""
        Exit Sub
    End If
    'Lookup values based on control
    With Me
        .TxBx1 = Application.WorksheetFunction.VLookup(Me.CmbBX1, rng, 2, 0)
        .TxBx2 = Application.WorksheetFunction.VLookup(Me.CmbBX1, rng, 3, 0)
    End With
End Sub