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



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

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

如果未精制代码,请原谅。我需要它的工作不仅是最有效的记忆力,尽管始终避免了不必要的混乱。感谢您的帮助。

此方法的存在为参数,而不是字典值。

LUT.exists(sval)

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

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

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

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

相关内容

最新更新