使用 VBA 用户表单搜索列表的代码

Code to search a list with a VBA Userform

我正在尝试在 VBA 中创建一个用户表单,它将在另一个 sheet 中搜索列表并显示所有匹配结果,是否也可以让该数据默认显示到 then通过搜索框值缩小范围?

它会搜索列表中的三列,但如果找到匹配项,理想情况下它会显示第一列和第三列的数据,中间列无关紧要,但需要保留其他代码。

那么您可能需要 select 将其中一个结果显示在工作簿的特定文件夹中(第一列的结果显示在一个单元格中,第二列的结果显示在其旁边的单元格中)。

我对用户表单完全陌生,所以像这样的任务非常艰巨,我什至不确定如何从 sheet.

激活表单

欢迎任何反馈,我会评论我在网上找到的任何有用代码。

完成了我所追求的大部分目标:

    Private Sub SearchButton_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual

    On Error GoTo ErrorHandler

    Workbooks("Form1.xlsm").Worksheets("Employees").Visible = True

    ActiveWorkbook.Sheets("Employees").Activate
    Employee = EmployeeName.Value
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    ActiveSheet.Range("$A:$C$" & lastrow).AutoFilter Field:=1, Criteria1:= _
        "=*" & Employee & "*", Operator:=xlAnd

    Workbooks("Form1.xlsm").Worksheets("Temp").Visible = xlSheetVisible
    Workbooks("Form1.xlsm").Worksheets("Temp").Range("A1:AFD1000000").ClearContents

    'validation to stop the form breaking if a nane is searched that doesnt exist
    Range("A1000000").Select
    Selection.End(xlUp).Select
    If ActiveCell.Value = "KeyID" Then GoTo validationend

    'Take the data that has been filtered by employee name and store it in a temp worksheet
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy
    Workbooks("Form1.xlsm").Worksheets("Temp").Activate
    Range("A1").Select
    ActiveSheet.Paste

    'Delete any data that is irrelevant at this stage
    Range("D:D").Delete Shift:=xlToLeft
    Range("E:E").Delete Shift:=xlToLeft
    Range("G:AZ").Delete Shift:=xlToLeft
    lastrow = Range("A" & Rows.Count).End(xlUp).Row

    Dim rngName As Range
    Dim ws As Worksheet
    Dim i As Integer

    Set ws = Worksheets("Temp")
    For i = 1 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row Step 1
        If ws.Cells(i, 1).Value <> vbNullString Then Me.ListBox.AddItem ws.Cells(i, 1).Value
    Next i

validationend:
    Workbooks("Form1.xlsm").Worksheets("Form").Activate

    'Workbooks("Form1.xlsm").Worksheets("Temp").Visible = xlSheetVeryHidden

    'Workbooks("Form1.xlsm").Worksheets("Employees").Visible = xlSheetVeryHidden

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.Calculation = xlCalculationAutomatic

    Exit Sub

ErrorHandler:
    MsgBox ("Error: Name not found. Please check your spelling and try again.")

    Workbooks("Form1.xlsm").Worksheets("Form").Activate

    'Workbooks("Form1.xlsm").Worksheets("Temp").Visible = xlSheetVeryHidden

    'Workbooks("Form1.xlsm").Worksheets("Employees").Visible = xlSheetVeryHidden

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.Calculation = xlCalculationAutomatic
End Sub

效果不是很好,所以如果您需要更多答案,我会尽快提出相关问题。