比较两个arrays与Excel VBA

至于这个问题,我需要能够将Variant数组A中的所有数据与Variant数组B中的所有数据进行比较。我知道我需要某种双循环(因此每个A值都会针对所有B值进行检查),但我无法弄清楚如何去做。 以下是我到目前为止:

Sub Button_Click() Dim trgtRange As Variant Dim tempRange As Variant Set myRange = ThisWorkbook.Sheets(1).Range("L:L") For Each cell In myRange If IsEmpty(cell) Then ActiveCell.Offset(-1, 0).Select currentRow = ActiveCell.Row Set trgtRange = Range("L2:L" & currentRow) Exit For End If Next cell Set tempRange = Range("A1:A" & currentRow - 1) ' Insert a double loop here End Sub 

所以, trgtRange是变体A和tempRange是变体B.我知道我可以设置变种B有点容易,但我已经这样做了。 毕竟,代码应该抛光作为最后的手术。

你可能想知道为什么变种A和B是完全一样的。 那么,那是因为我需要对它们进行比较,以便我可以find彼此接近的值(即10000和12000),并且需要包含某种宽容度。

这是我的答案。 为什么你需要两个循环来做到这一点。 一些相对的寻址处理这个问题相当好。 设置一个这样的电子表格为例:

电子表格布局

而你的代码就是这个

 Sub Button_Click() Dim dblTolerance As Double Dim tmp As Range 'Get source range Set tmp = ActiveSheet.Range("A2") 'Get tolerance from sheet or change this to an assignment to hard code it dblTolerance = ActiveSheet.Range("D13") 'use the temporary variable to cycle through the first array Do Until tmp.Value = "" 'Use absolute function to determine if you are within tolerance and if so put match in the column 'NOTE: Adjust the column offset (set to 4 here) to match whichever column you want result in If Abs(tmp.Value - tmp.Offset(0, 2).Value) < dblTolerance Then tmp.Offset(0, 4).Value = "Match" Else tmp.Offset(0, 4).Value = "No Match" End If 'Go to the next row Set tmp = tmp.Offset(1, 0) Loop 'Clean up Set tmp = Nothing End Sub 

代码中的注释说明了它的工作原理。 这优于双循环,因为相对引用速度更快,内存使用效率更高,并且只需在每一行进行一次传递。

如果您因为某种原因需要使用双循环,请告诉我,但是这种方法在性能方面逊色。 希望这可以帮助。