简体   繁体   English

Excel VBA-计算重复项

[英]Excel VBA - count the duplicates

I have two arrays which contains string values in them. 我有两个数组,其中包含字符串值。 Let us consider the example as below. 让我们考虑以下示例。

  • Array 1: Computer science, Artificial Intelligence 阵列1:计算机科学,人工智能
  • Array 2: Eclipse, MS, RAD, Linux, Artificial Intelligence 数组2:Eclipse,MS,RAD,Linux,人工智能

I need to find the number of duplicates in both of my arrays. 我需要找到两个数组中重复项的数量。 In the above case, I need the total duplicate value as 1 (since Artificial Intelligence is in both Array1 and Array2). 在上述情况下,我需要总重复值为1(因为Array1和Array2中都包含人工智能)。 Is there a way to do this in VBA? 有没有办法在VBA中做到这一点?

This function assumes that arr2 is a 1-dimensional array: 此函数假定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

To use it: 要使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM