如何解决使用集合对象在 Excel VBA 中存储来自 Recordset 的匹配项
使用 Excel VBA,我试图在 sqlite 表中搜索出现在文件名中的名称。
在下面的代码中,我有 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
...
在执行最后一个 rst
之前将 Nothing
变量设置为 Debug.Print
,并且可能会对添加到集合中的 ![person_name]
引用产生影响。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。