![](/img/trans.png)
[英]Custom function in excel vba that lookup a cell value in a range that returns multiple match values and combine them in one cell
[英]Excel VBA function to lookup value in a Cell range
我知道如何使用match和index在excel中執行此操作。 我的電子表格有很多這些查找,但必須易於審核。
在純excel公式中,它很簡單:
=index(match()...match()) of the table
雖然容易做到,但如果表的大小發生變化等,它會產生很大的影響。 公式的可讀性也很差。 表格以及標題和列的命名范圍使得進行故障排除變得更加困難。
Col1 Col2 Col3
Row1 1 2 3
Row2 4 5 6
Row3 7 8 9
我命名此范圍,行和列名稱分別為第一行和第一列。
所以Excel變量將被稱為test_table。
想寫一個我可以調用的VBA函數:
=VBAlookup("Row2", "Col2", test_table)
returns 5
我正在使用python與DataNitro和pandas輕松地進行拼接。 不擅長VBA,所以在VBA寫這篇文章會花費很長時間。 當然,我不是第一個或只是尋找這個功能,但谷歌搜索似乎沒有讓我到任何地方。
不想回答我自己的問題,但到目前為止我的解決方案(改編自@John Bustos的答案如下)是:
Public Function VBAlookup(RowName As Variant, ColName As Variant, Table As Range) As Variant
Dim RowNum As Integer
Dim ColNum As Integer
VBAlookup = "Not Found"
For RowNum = 1 To Table.Rows.Count
If Table.Cells(RowNum, 1) = RowName Then
For ColNum = 1 To Table.Columns.Count
If Table.Cells(1, ColNum) = ColName Then
VBAlookup = Table.Cells(RowNum, ColNum)
End If
Next ColNum
End If
Next RowNum
End Function
這會以正確的格式獲取任何類型的內容,如果值不在表中,也會給出一些反饋
這應該這樣做:
Public Function VBAlookup(RowName As String, ColName As String, Table As Range) As String
Dim RowNum As Integer
Dim ColNum As Integer
VBAlookup = ""
For RowNum = 1 To Table.Rows.Count
If Table.Cells(RowNum, 1).Text = RowName Then
For ColNum = 1 To Table.Columns.Count
If Table.Cells(1, ColNum).Text = ColName Then
VBAlookup = Table.Cells(RowNum, ColNum).Text
End If
Next ColNum
End If
Next RowNum
End Function
請注意,我沒有進行任何錯誤檢查等,這是一個很好的做法!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.