简体   繁体   English

希望创建一个Excel用户窗体以根据参数从工作表中提取信息

[英]Looking to create an excel userform to pull information from worksheet based on parameters

I have a worksheet with thousands of information on start-end series of machine ID numbers. 我有一个工作表,其中包含有关机器ID编号的起止系列的数千个信息。 These are further grouped into years 2012, 2013, 2014, 2015. So in each year there are 2 columns of numbers: start and end. 这些又分为2012、2013、2014、2015年。因此,每年都有2列数字:开始和结束。 These refer to the start and end of the machinery ID. 这些指的是机器ID的开始和结束。

   Model     2012           2013          2014        2015
            Start  End    Start  End    Start End   Start End
    XYZ     00123  0800   08015  0834   0654  0756  1320  1390
    ABC     00010  00200  1500   1600    etc...

I am confused how to make a search with userform that will identify the model name, then search for its ID with the table and return the year where that ID falls in. 我很困惑如何使用将标识模型名称的用户表单进行搜索,然后使用表格搜索其ID并返回该ID所属的年份。

  • Search parameter 1: Match and return the model name typed in the search 搜索参数1:匹配并返回在搜索中键入的型号名称
  • Search parameter 2: Find where the ID is in the entire table 搜索参数2:查找ID在整个表中的位置

Result: If I type in "XYZ" and the ID number "0756" in the search then that should giving me an answer of 2014. 结果:如果我在搜索中输入“ XYZ”和ID号“ 0756”,则应该给出2014的答案。

If we assume the data in the question starts at cell A1 this would be a possible solution. 如果我们假设问题中的数据始于单元格A1,那么这可能是一种解决方案。

Sub TestFindYear()
    MsgBox FindYearByModelAndId("XYZ", 755), vbInformation
End Sub

Public Function FindYearByModelAndId(searchModel As String, serachID As Double) As String
    Dim wsData As Worksheet
    Set wsData = ThisWorkbook.Worksheets("Data") 'we assume that the worksheet name to search in is "Data"

    Dim modelRow As Long, lastCol As Long

    'find the row number of the model in column A
    On Error GoTo errorModelNotFound 'throw an error if model was not found
        modelRow = Application.WorksheetFunction.Match(searchModel, wsData.Range("A:A"), 0)
    On Error GoTo 0

    With wsData
        lastCol = .Cells(modelRow, .Columns.Count).End(xlToLeft).Column 'get the last used column of the model row
        Dim i As Long
        For i = 2 To lastCol Step 2 'loop through the columns of the model row
            If serachID >= .Cells(modelRow, i).Value And _
               serachID <= .Cells(modelRow, i + 1) Then 'check if ID is in between start and end
                FindYearByModelAndId = .Cells(1, i).Value 'return the year of row 1
                Exit For
            End If
        Next i
    End With

    If FindYearByModelAndId = vbNullString Then
        FindYearByModelAndId = "ID not found."
    End If

    Exit Function
errorModelNotFound:
    FindYearByModelAndId = "Model not found."
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM