2015-09-01 69 views
0

我一直在试图弄清楚一段时间。最初我搜索了Google,发现了一些(或多或少)我正在尝试做的事情,但似乎停留在我迄今为止的代码上。本质上,我试图比较两个数组之间的唯一变量,并在完美匹配时返回结果(如果一个拥有唯一值代表另一个数组的子集,则这不会是完美匹配,所有值和数值匹配具有相同唯一值的数组VBA(Excel)

从我已经包含在下面的代码;如果我比较一个数组[范围(“B2:b6”)值{1,2,3}]到第二个数组[[范围( “D10:D11”)的值为{1,2}],我收到了一个肯定的匹配。然而,我试图做的事情(和值顺序无关紧要)是{1,2 ,3}将是第二个值为{1,2,3}的数组(也可以是{3,2,1},因为顺序无关紧要)

我猜这是由于数组类型我正在使用和事实下界从0开始。我也可能是完全错误的。我尝试过没有成功的尝试。

有什么想法?欢迎任何建议。谢谢! (下面有不同的价值观包括图片)

enter image description here

Function UniqueVal(ByRef Arr1, ByRef Arr2) 

    If TypeOf Arr1 Is Range Then Arr1 = Arr1.Value2 
    If TypeOf Arr2 Is Range Then Arr2 = Arr2.Value2 

    Dim e, x, i As Long 

    With CreateObject("scripting.dictionary") 
     .CompareMode = 1 
     For Each e In Arr1 
      If Len(e) Then .Item(e) = Empty 
     Next 
     For Each e In Arr2 
      If .Exists(e) Then 
       .Item(e) = 1 
      Else 
       .RemoveAll 
       UniqueVal = .Keys 
       Exit Function 
      End If 
     Next 

     x = Array(.Keys, .Items) 
     .RemoveAll 
     For i = 0 To UBound(x(0)) 
      If x(1)(i) = 1 Then .Item(x(0)(i)) = Empty 
     Next 
     If .Count Then UniqueVal = .Keys 
    End With 

End Function 

'and the below sub which calls the above function 

Sub iTestIntersectionX() 

array4 = Join(UniqueVal(Worksheets("arrayTest2").Range("B2:B6"), Worksheets("arrayTest2").Range("D10:D11")), vbLf) 
Worksheets("arrayTest2").Range("H20").value = array4 

If Worksheets("arrayTest2").Range("H20").value <> "" Then 
    MsgBox "Match Found!" 
    Else 
    MsgBox "No Match Found!" 
End If 

End Sub 
+0

是你与总是会从未来的范围内工作的价值? –

回答

-2

有你可以进入到一个名为VLOOKUP单元格的公式。它需要几个参数。它查找单元格列表中的一个单元格的值,并返回单元格列表中匹配单元格旁边的单元格的值。

0

这将返回True如果传入的两个范围具有相同的一组唯一值的(以任意顺序或频率)

Function HaveSameValues(rng1 As Range, rng2 As Range) 
Dim c As Range 

    For Each c In rng1.Cells 
     If Len(c.Value) > 0 And IsError(Application.Match(c.Value, rng2, 0)) Then 
      SameValues = False 
      Exit Function 
     End If 
    Next c 
    For Each c In rng2.Cells 
     If Len(c.Value) > 0 And IsError(Application.Match(c.Value, rng1, 0)) Then 
      SameValues = False 
      Exit Function 
     End If 
    Next c 

    SameValues = True 

End Function