2015-12-14 142 views
0

我有一個索引/匹配查找公式,我想在ActiveX窗體中加入。該代碼是VBA索引匹配

=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 

但是這給了我「運行時錯誤‘9’:下標越界」當我點擊搜索按鈕。我對Excel和VBA非常新,所以如果任何人有任何想法,至少可以讓一個ListBox來填充,以便我可以將代碼調整到其他我會感激的地方。作爲參考,我在Windows 7上使用Excel 2010。

回答

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,如果只有一個值顯示?,請使用textbox代替)

第三點,對於運行時錯誤,最好是通過顯示錯誤行來給出正確的調試。但是,我建議您檢查表格是否已經存在於數據的工作表中。如果確實如此,那麼檢查其名稱匹配你已經把你的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 
+0

你好,感謝您的回覆。 – dubyarly

+0

我發現一些網站建議使用INDEXMATCH比VLOOKUP更通用,所以我就使用了它。此外,謝謝指出列表框問題 - 我注意到事後並將其更改爲文本框。感謝您的建議,我會嘗試您的建議,看看我能想出什麼。 – dubyarly