Excel VBA - 计算重复项

时间:2013-08-22 21:57:16

标签: vba excel-vba excel

我有两个数组,其中包含字符串值。让我们考虑下面的例子。

  • 数组1:计算机科学,人工智能
  • 数组2:Eclipse,MS,RAD,Linux,人工智能

我需要找到两个数组中重复的数量。在上面的例子中,我需要总重复值为1(因为人工智能在Array1和Array2中)。有没有办法在VBA中执行此操作?

1 个答案:

答案 0 :(得分:1)

此函数假定arr2是一维数组:

Function ArrDupCount(ByVal arr1 As Variant, ByVal arr2 As Variant) As Long

    Dim varElement As Variant
    Dim lMatch As Long

    On Error Resume Next
    For Each varElement In arr1
        lMatch = 0
        lMatch = WorksheetFunction.Match(varElement, arr2, 0)
        If lMatch > 0 Then ArrDupCount = ArrDupCount + 1
    Next varElement
    On Error GoTo 0

End Function

使用它:

Sub tgr()

    Dim arr1 As Variant
    Dim arr2 As Variant

    arr1 = Array("Computer science", "Artificial Intelligence")
    arr2 = Array("Eclipse", "MS", "RAD", "Linux", "Artificial Intelligence")

    MsgBox ArrDupCount(arr1, arr2)  ' => 1

End Sub