希望创建一个excel用户表单,根据参数从工作表中提取信息
我有一张工作表,上面有数千条关于机器ID号开始-结束系列的信息。这些进一步分为2012年、2013年、2014年和2015年。因此,每年有两列数字:开始和结束。这些是指机器ID的开始和结束希望创建一个excel用户表单,根据参数从工作表中提取信息,excel,vba,Excel,Vba,我有一张工作表,上面有数千条关于机器ID号开始-结束系列的信息。这些进一步分为2012年、2013年、2014年和2015年。因此,每年有两列数字:开始和结束。这些是指机器ID的开始和结束 Model 2012 2013 2014 2015 Start End Start End Start End Start End XYZ 00123 0800 08015 0
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所在的年份
- 搜索参数1:匹配并返回搜索中键入的模型名称
- 搜索参数2:查找ID在整个表中的位置
结果:如果我在搜索中输入“XYZ”和ID号“0756”,那么我的答案应该是2014。如果我们假设问题中的数据从单元格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
子测试findyear()
MsgBox FindyerarbymodelandId(“XYZ”,755),vbInformation
端接头
公共函数FindYearByModelAndId(searchModel为String,serachID为Double)为String
将wsData设置为工作表
Set wsData=thiswoolk.Worksheets(“Data”)'我们假设要搜索的工作表名称为“Data”
Dim modelRow尽可能长,lastCol尽可能长
'在A列中查找模型的行号
错误时转到errorModelNotFound'如果找不到模型,则抛出错误
modelRow=Application.WorksheetFunction.Match(searchModel,wsData.Range(“A:A”),0)
错误转到0
使用wsData
lastCol=.Cells(modelRow、.Columns.Count).End(xlToLeft).Column'获取模型行的最后一个使用的列
我想我会坚持多久
对于i=2到lastCol,步骤2'循环通过模型行的列
如果serachID>=.Cells(modelRow,i).值和_
塞拉奇德:2013年的数字怎么可能从08015开始,到0834结束,这对我来说毫无意义。只是打字错误?ID0756
的搜索参数是否需要匹配开始或结束,或者它是否需要介于开始和结束之间?哦,对不起,如果我键入的数字等于或介于开始和结束序列之间,则应为08034,这应该会回到它所属的那一年。我正在用逻辑运算符研究vlookup,但不确定这是否是最好的方法,因为可能会有更多的“年”来欢迎StackOverflow。请注意,这不是免费的代码编写服务。然而,我们渴望帮助其他程序员(和有抱负的人)编写他们自己的代码。请阅读上的帮助主题。您可能还想在这样做的同时获得一枚徽章。之后,请使用您迄今为止编写的VBA代码更新您的问题,以便完成您希望完成的任务。我们会在这里等你。准备好帮助您完成代码。谢谢Peh。这超出了我的预期。我会给你的代码一个尝试,并张贴最后的代码在这里时,所有的工作。