检查数组中是否存在字符串 - 这里的错误是什么?

时间:2017-06-05 21:44:40

标签: excel-vba vba excel

我正在尝试从数组中删除重复项并构建一个简化数组。我收到一个对象必需的错误。这就是我在做什么 -

Dim LUT as object, baseArray() as string, sval as variant
'Dim sval as string ... ignore this
For I = 1 to n
    Set LUT = CreateObject("Scripting.Dictionary")
    ... other stuff
    u = 1
    for each sval in baseArray
        if not LUT.exists(sval) then 
            do something...
            LUT.Add u, sval
        end if
    u = u + 1
    next sval
    Set LUT = nothing
Next I

如果代码是未定义的,请原谅。虽然总是要避免不必要的混乱,但我需要它比最有效的内存更有效。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

此方法存在将字典键作为参数而不是字典值。

LUT.exists(sval)

您可能想要检查其他数据结构,例如集合和此方法 Collection.contains

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.collection.contains(v=vs.110).aspx

答案 1 :(得分:0)

如果您想在没有脚本字典的情况下执行此操作,可以使用字符串比较来执行此操作:

Sub DeDupeArray()
Dim MyArr As Variant, NewArr() As String, X As Long
MyArr = Array("Hello", "World", "This", "World", "Is Some", "World", "Data")
ReDim Preserve NewArr(0)
For X = LBound(MyArr) To UBound(MyArr)
    If InStr(1, "|" & Join(NewArr, "|") & "|", "|" & MyArr(X) & "|") = 0 Then 'Test if the element in MyArr exists in NewArr
        If NewArr(0) <> "" Then ReDim Preserve NewArr(UBound(NewArr) + 1) 'Add another element to the array only if it's not the first element to be entered (otherwise will be blank in address 0)
        NewArr(UBound(NewArr)) = MyArr(X) 'Add Element X from MyArr into the last address of NewArr
    End If
Next
MsgBox "Old Array: " & Join(MyArr, "|") & vbLf & vbLf & "New Array: " & Join(NewArr, "|")
End Sub