如何在VBA中检查多个值是否相等?

时间:2015-04-22 17:43:52

标签: 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)

谢谢!

3 个答案:

答案 0 :(得分:1)

快速而肮脏的方法是使用Dictionary,它需要一个唯一的键。只需继续从数组中转储数字,直到找到已经在Dictionary中的数字。只需将其转换为函数并将数组传递给它:

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

答案 1 :(得分: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

答案 2 :(得分:0)

作为@ ja72上面给出的public String exmp(StringBuilder sql, String table){ authCache = new BasicAuthCache(); basicAuth = new BasicScheme(); authCache.put(target, basicAuth); localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); String postJsonstr=null; try { HttpPost httpPost = new HttpPost(API_URL); JSONObject sbjson = new JSONObject(); sbjson.put("format", "csv"); sbjson.put("version", "1.0"); sbjson.put("name", table); sbjson.put("encrypted", "none"); JSONArray array = new JSONArray(); JSONObject item = new JSONObject(); item.put("name", table); item.put("query", sql); item.put("type", "export"); array.put(item); sbjson.put("queries", array); httpPost.addHeader("accept", jsonContentType); StringEntity postEntity = new StringEntity(sbjson.toString()); posEnt.setContentType(jsonContentType); httpPost.setEntity(posEnt); CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext);} 答案的略微变化,此函数应该能够采用任何类型的任何一组简单值,并确定它们是否全部相同。 (这是Strings的第四个测试行的例外,其中Collection键不区分大小写。)我正在利用散列算法将键添加到Collection以确保独特的烦躁。

Collection