在二维数组vba中searchstring

我有以下格式的二维数组。 (不确定如何格式化它以表格格式显示,第一列和第二列各有1个字符,第三列是2个字符)

a 1 aa a 2 ab b 1 ba b 2 bb c 1 ca c 2 cb d 1 da d 2 db e 1 ea e 2 eb f 1 fa f 2 fb 

我需要先在第一列中search“c”。 如果发现,我需要在第二个search“2”,并在第三个find相应的值。 在这种情况下,我最后需要值“cb”。

这是我到目前为止,但它不能正常工作,因为我没有看到预期的结果

 Public Sub Readinto_array() Dim TheArray As Variant Dim i As Long, j As Long, k As Long Dim found As Boolean TheArray = Range("G20:I31").Value found = False For i = LBound(TheArray) To UBound(TheArray) For j = LBound(TheArray, 2) To UBound(TheArray, 2) MsgBox TheArray(i, j) If TheArray(i, j) <> "c" Then Exit For Else If StrComp(TheArray(i, j + 1), "2", vbTextCompare) = 0 Then MsgBox "found" found = True Exit For End If End If Next j If found Then Exit For End If Next i End Sub 

不知道为什么你必须循环列,因为你知道总是有3 …所以这似乎更容易。

 Public Sub Readinto_array() Dim TheArray As Variant Dim i As Long TheArray = Range("G20:I31").Value For i = LBound(TheArray) To UBound(TheArray) If TheArray(i, 1) = "c" And TheArray(i, 2) = "2" Then MsgBox (TheArray(i, 3)) End If Next i End Sub 

或者使用先天的excel对象进一步简化。

 Public Sub Readinto_array() Dim MyRange As Range Set MyRange = Range("G20:I31") For Each cell In MyRange If cell.Value = "c" And Cells(cell.Row, cell.Column + 1) = "2" Then MsgBox (Cells(cell.Row, cell.Column + 2).Value) End If Next End Sub 

你也可以用工作表公式来做到这一点。 例如,如果E1包含您的column1值; 和B1你的column2值,请尝试:

 G2: =INDEX(ThirdColumn,SUMPRODUCT((FirstColumn=E1)*(SecondColumn=E2)*ROW(ThirdColumn))) 

在这里输入图像说明

我看到一个像结构树,并认为XML,但保持简单使用一个字典…

在VBA编辑器中 – 使用工具/引用菜单添加对Microsoft脚本运行时的引用。

编写一个函数来创build字典:

 Public Function LookErUp() As Dictionary Dim i As Integer Dim d As Dictionary Set d = New Dictionary Dim col1() As Variant col1 = Array("a", "b", "c", "d", "e", "f") Dim col2 As Dictionary For i = 0 To UBound(col1) Set col2 = New Dictionary col2.Add 1, col1(i) & "a" col2.Add 2, col1(i) & "b" d.Add col1(i), col2 Next Set LookErUp = d End Function 

您可以使用字典testing程序testing:

 Public Sub Test() Dim ld As Dictionary Set ld = LookErUp If ld.Exists("c") Then If ld("c").Exists(2) Then MsgBox "Found " & ld("c")(2) End If End If End Sub 

尝试创build第三列,您连接三个以前的列的值,即在D1中,您将有=A1&B1&C1 。 接下来在你使用vlookupmatch 。 如果你没有指定完全匹配,那么万一有c 1的多个条目,你会得到第一个或最后一个,这取决于使用的比较types。