【问题标题】:VBA Index MatchVBA 索引匹配
【发布时间】:2015-12-14 17:23:04
【问题描述】:

我有一个索引/匹配查找公式,我想将其合并到 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。

到目前为止,我得到了:

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

但是当我单击 SearchButton 时,这给了我“运行时错误 '9':下标超出范围”。我对 Excel 尤其是 VBA 很陌生,所以如果有人有任何想法至少要填充一个 ListBox,以便我可以将代码调整为其他代码,我将不胜感激。作为参考,我在 Windows 7 上使用 Excel 2010。提前致谢!

【问题讨论】:

    标签: vba excel excel-2010


    【解决方案1】:

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

    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 方法将返回用户在列表框中选择的值,而不是相反的方式。 (顺便说一句,如果您只有一个要显示的值,为什么要使用列表框?请改用文本框)

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

    编辑: 用户友好的解决方案之一如下:

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

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

    3 - 定义一个 sub 接受该输入行并使用它来填充数据的文本框

    函数例如:

    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
    

    【讨论】:

    • 我发现几个网站建议使用 INDEXMATCH 比 VLOOKUP 更通用,所以我选择了它。另外,感谢您指出列表框问题-事后我注意到并将它们更改为文本框。谢谢你的建议,我会试试你的建议,看看我能想出什么。
    猜你喜欢
    • 2015-12-15
    • 2021-08-25
    • 2011-11-26
    • 2015-10-30
    • 2014-11-14
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多