使用集合对象将记录集中的匹配存储在 Excel VBA

Using collection object to store matches from Recordset in Excel VBA

使用 Excel VBA,我正在尝试通过 SQLite table 搜索文件名中出现的名称。

在下面的代码中,我使用 NamesFound 集合对象来存储姓名。

当我遍历记录集时,我可以将名字添加到 NamesFound 并打印它们。

关闭记录集并销毁变量后,当我打印集合中的项目数时 (NamesFound.count),我得到一个与文件名中匹配名称的数量相匹配的数字。

但是,当我尝试打印集合中的任何元素时,我收到错误消息“对象不再有效”。

知道为什么会这样吗?

Option Explicit

Sub SQLiteMatch()

    Dim strSQL As String, fn As String
    
    Dim NamesFound As Collection
    Set NamesFound = New Collection
    
    Dim conn As Object
    Set conn = CreateObject("ADODB.Connection")
    
    Dim rst As Object
    Set rst = CreateObject("ADODB.Recordset")
    
    fn = "C:\Clark Gable & Vivian Leigh in Gone With The Wind.mp4"
    
    conn.Open "DRIVER=SQLite3 ODBC Driver;Database=C:\Path\To\cast&crew.db;"
    
    strSQL = "SELECT id, person_name from People"
    
    rst.Open strSQL, conn, 1, 1
    
    With rst
        .MoveFirst
        Do Until .EOF
            If InStr(1, fn, ![person_name]) > 0 Then
                NamesFound.Add ![person_name]
                Debug.Print "Names found: " & NamesFound.Count & " - " & _
                    NamesFound(NamesFound.Count)                                '<<< Works fine
            End If
            .MoveNext
        Loop
    End With
    
    rst.Close
    
    Set rst = Nothing
    Set conn = Nothing
    
    Debug.Print NamesFound(1) '<<< Error #3420: Object is no longer valid -
                              ' same error for NamesFound.item(1) and NamesFound(1).Value

End Sub

也许试试:

...
'copy ![person_name] to a variable before adding to the Collection      Dim personNameCopy As String        With rst            .MoveFirst          Do Until .EOF
        personNameCopy = ![person_name]
        If InStr(1, fn, personNameCopy ) > 0 Then
            NamesFound.Add personNameCopy 
            Debug.Print "Names found: " & NamesFound.Count & " - " & _
                NamesFound(NamesFound.Count)                                '<<< Works fine
        End If
        .MoveNext           Loop        End With
...

在执行最后一个 Debug.Print 之前,rst 变量设置为 Nothing,并且可能会对添加到集合中的 ![person_name] 引用产生影响。