2

至于问题,我需要能够将 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是变体 AtempRange还是变体 B。我知道我可以更轻松地设置变体 B,但我已经这样做了。毕竟,无论如何,代码都应该作为最后的操作进行抛光。

您可能想知道为什么变体 A 和 B 完全相同。嗯,那是因为我需要对它们进行比较,这样我才能找到彼此接近的值(即 10000 和 12000),并且我需要为它加入某种容差。

4

1 回答 1

1

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

电子表格布局

你的代码就是这样

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

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

如果您出于某种原因需要使用双循环,请告诉我,但这对于这种方法来说性能较差。希望这可以帮助。

于 2014-08-07T18:45:05.417 回答