VBA指数匹配

时间:2015-12-14 17:23:05

标签: excel vba excel-vba excel-2010

我有一个索引/匹配查找公式,我想将其合并到ActiveX表单中。代码是

=IF(A2="","No Search Criteria",IFERROR(INDEX(AssetList,MATCH(A2,AssetList[Asset '#],0),1),INDEX(AssetList,MATCH(A2,AssetList[Serial '#],0),1))

) 这允许我搜索项目的资产编号或序列号并返回其资产编号。包含此代码的单元格旁边的单元格具有修改版本,以返回其序列号,项目编号和棘轮大小。我正在尝试创建一个将执行这些相同功能的表单,允许用户在SearchCriteriaTextBox中键入资产或序列号,并在单击SearchButton时将相应的值返回到AssetNumberListBox,SerialNumberListBox,ItemNumberListBox和RatchetSizeListBox。 / p>

到目前为止,我已经:

Private Sub SearchButton_Click()        
AssetNumberListBox.Value = Application.WorksheetFunction.Match(SearchCriteriaTextBox.Value, Sheet2.ListObjects("AssetList").ListColumns("Asset#").DataBodyRange, False)
SerialNumberListBox.Value =
ItemNumberListBox.Value =
RatchetSizeListBox.Value =


End Sub

但是这给了我"运行时错误' 9':下标超出范围"当我点击SearchButton。我是Excel的新手,特别是VBA,所以如果有人有任何想法,至少得到一个ListBox来填充,所以我可以调整代码给其他人我很感激。作为参考,我在Windows 7上使用Excel 2010.提前感谢!

1 个答案:

答案 0 :(得分:0)

基本上,我理解你的数据的表结构如下:

Asset Number | Serial Number | Item Number | Rachet Size

第一点是查找数据:

为什么使用返回位置的MATCH函数?:

AssetNumberListBox.Value = Application.WorksheetFunction.Match(SearchCriteriaTextBox.Value, Sheet2.ListObjects("AssetList").ListColumns("Asset#").DataBodyRange, False)

您应该使用WorksheetFunction.VLOOKUP来返回值。

然后,在第二点,为了填充列表框,您必须使用Additem方法。 Value方法将由用户返回列表框中的选定值,而不是相反的方式。 (顺便说一句,为什么使用Listbox如果你只有一个值可以显示?,请改用文本框)

第三点,对于运行时错误,最好通过显示错误行来进行正确的调试。但是,我建议您检查表格是否已存在于数据的工作表中。如果是,请检查其名称是否与您在VBA代码中的名称相匹配(列名称相同)

编辑: 其中一个用户友好型解决方案如下:

1 - 创建自己的用户表单,基本上有4个文本框和一个用于搜索的按钮。

2 - 定义您自己的函数,该函数返回包含目标数据的行。

3 - 定义一个获取该输入行并使用它来填充带有数据的文本框的子

该功能可以例如:

Function Row_Of_Data(Asset_Num as String, Serial_Num as String, Search_Table as String) as Long
Dim Target_Data as Range
Dim T_Row as Long
'Now, we set a range that contains all of the data in the table object in your worksheet
On Error Goto Unfound 
Set Target_Data = Sheet2.ListObjects(Search_Table).DataBodyRange
If Asset_Num <> "" AND Serial_Num = ""  Then 
     Row_Of_Data = WorksheetFunction.Match(Asset_Num,Target_Data.Columns(1),False)
Elseif Serial_Num <> "" AND Asset_Num = "" Then
   Row_Of_Data = WorksheetFunction.Match(Asset_Num,Target_Data.Columns(2),False)
Else 
   Row_Of_Data = WorksheetFunction.Match(Asset_Num,Target_Data.Columns(1),False)
End if
Exit Function
Unfound:
Row_Of_Data = 0


End Function
相关问题