2015-04-22 109 views
3

我想在工作表中打印一個包含八個數字的列表,但前提是它們都是唯一的。如何檢查VBA中的多個值不相等?

理想的代碼將是沿

If a <> b <> c Then 

線的東西而不是

If a <> b And a <> c And b <> c Then 

這是可能的,因爲該值是從一個陣列使用的代碼以下稱爲:

Cells(2, 8) = numarr(i) 
Cells(2, 9) = numarr(j) 
Cells(2, 10) = numarr(k) 
Cells(2, 11) = numarr(l) 
Cells(3, 8) = numarr(m) 
Cells(3, 9) = numarr(n) 
Cells(3, 10) = numarr(o) 
Cells(3, 11) = numarr(p) 

謝謝!

+0

一個非常快速的方式是添加了所有的數字:'A + B + C + d + E + F + G + H = sumtotal',然後比較''用一個sumtotal' * 8'。基本上,'if(a * 8)= sumtotal then all_numbers_are_equal'。可能比一個大邏輯語句更快。 (順便說一句,你的第一個'If'語句是不正確的語法,不會編譯。) – PeterT

+0

是的,我知道第一個聲明不起作用,這應該是我想要做的事情的一個演示。將所有數字加起來的解決方案非常有用,它可以非常輕鬆地解決我的問題!就像你所說的,比一系列邏輯語句快得多! – Sean

+0

@PeterT - 找不到所有唯一的數字或找出它們是否都一樣無效。考慮(以a-h的順序):6,7,7,5,5,4,4,10 - >(6 * 8)= 6 + 7 + 7 + 5 + 5 + 4 + 4 + 10。或者所有唯一的數字:「6,1,8,5,10,2,9,7 - >(6 * 8)= 6 + 1 + 8 + 5 + 10 + 2 + 9 + 7」。 – Comintern

回答

1

快速和骯髒的方式來做到這一點是與一個字典,它需要一個獨特的關鍵。只需在數組中輸入數字,直到您點擊詞典中已有的數字。只是使它成爲一個功能,您的數組傳遞給它:

Private Function AllUnique(incoming As Variant) As Boolean 

    If Not IsArray(incoming) Then Err.Raise 13 

    Dim candidates As Scripting.Dictionary 
    Set candidates = New Scripting.Dictionary 

    Dim index As Long 
    For index = LBound(incoming) To UBound(incoming) 
     If candidates.Exists(incoming(index)) Then Exit Function 
     candidates.Add incoming(index), index 
    Next index 

    AllUnique = True 

End Function 
0

我打算在直接比較法拋出:

Public Function AreEqual(ParamArray values() As Variant) As Boolean 
    Dim i As Long, j As Long, N As Long 
    Dim x As Double 
    N = UBound(values) + 1 
    For i = 1 To N - 1 
     x = values(i - 1) 
     For j = i + 1 To N 
      If values(j - 1) <> x Then 
       AreEqual = False 
       Exit Function 
      End If 
     Next j 
    Next i 
    AreEqual = True 
End Function 

爲了用作

If AreEqual(num1,num2,num3,...) then 
    ... 
End If 
0

由於由@ ja72給出的Collection答案的一個細微變化,這個函數應該能夠取任何類型的任何簡單值的集合,並確定它們是否全部相同。 (這是Strings第四條測試線的例外,其中Collection鍵不區分大小寫。)我利用散列算法將鍵添加到Collection以確保獨特性。

Option Explicit 

Sub Test() 
    Debug.Print AllValuesIdentical(14, 14, 14, 14, 14, 14, 14, 14, 14) 'true 
    Debug.Print AllValuesIdentical(5, 5, 5, 5, 5, 3, 5, 5)    'false 
    Debug.Print AllValuesIdentical("go", "go", "go", "go")    'true 
    Debug.Print AllValuesIdentical("go", "go", "go", "GO")    'also true 
    Debug.Print AllValuesIdentical(283.14, 283.14, 283.14)    'true 
End Sub 

Function AllValuesIdentical(ParamArray vals() As Variant) As Boolean 
    Dim uniqueCheck As Collection 
    Dim val As Variant 
    Set uniqueCheck = New Collection 
    On Error Resume Next 
    For Each val In vals 
     uniqueCheck.Add val, CStr(val) 
    Next val 
    If uniqueCheck.Count = 1 Then 
     AllValuesIdentical = True 
    Else 
     AllValuesIdentical = False 
    End If 
    On Error GoTo 0 
    Set uniqueCheck = Nothing 
End Function 
相關問題