我有一个子例程,仅当该项目不存在时才将其添加到集合中。这有效地将集合视为集合。 但是当调用子程序时,VBA 返回错误 424。
Private Sub SetUnion(ByVal e As String, ByVal Coll As Collection)
found = False
For n = 1 To Coll.Count
If Coll(n) = e Then
found = True
Exit For
End If
Next n
If found = False Then Coll.Add e
End Sub
当我用
调用它时Dim s1, C As Collection
For n = 1 To s1.Count
SetUnion s1(n), C #
Next n
我明白了
Run-time error ‘424’:
Object required
我做错了什么?
@braX
评论说您在 VBA 代码中使用了另一种编程语言的语法。
根据您的代码,您似乎正在尝试从字符串中提取唯一字符。
Option Explicit
Sub SetUnion(ByVal e As String, ByRef Coll As Collection)
Dim n As Long
If Not Coll Is Nothing Then
For n = 1 To Coll.Count
If Coll(n) = e Then
Exit Sub
End If
Next n
End If
Coll.Add e
End Sub
Sub test()
Dim sStr As String, oCol As Collection, n As Long
sStr = "abcabd"
Set oCol = New Collection
For n = 1 To Len(sStr)
SetUnion Mid(sStr, n, 1), oCol
Next n
For n = 1 To oCol.Count
Debug.Print oCol(n)
Next
End Sub
输出:
a
b
c
d