我有一个工作表,上面有成千上万的机器ID编号的起始系列信息。这些进一步分为2012年,2013年,2014年,2015年。因此,每年有2列数字:开始和结束。这些是指机械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...
我很困惑如何使用将识别模型名称的userform进行搜索,然后使用表格搜索其ID并返回该ID所在的年份。
结果:如果我输入" XYZ"和身份证号码" 0756"在搜索中那应该给我一个2014年的答案。
答案 0 :(得分:0)
如果我们假设问题中的数据从单元格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