我有一些代码循环遍历文件夹中的一堆文件,并将数据加载到记录集中,将文件名和记录集存储在字典中(作为键/值对)供以后使用。循环适用于前64个文件,但随后它给了我一个"未指定的错误"第65次对话尝试。代码在recordData.Open行中断(循环调用下面的函数,因此不显示For Each循环):
Public Function GetRecords(ByVal dataSrc as String) as ADODB.Recordset
Dim dir as String
Dim file as String
Dim recordData as ADODB.Recordset
Dim sql as String
Dim conn as String
dir = "C:\MyDirectory"
file = dataSrc & ".csv"
conn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & dir & ";" & _
"Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;"""
If DoesFileExist(dir & file) Then
sql = "select * from " & file & ";"
Set recordData = New ADODB.Recordset
recordData.CursorLocation = adUseClient
recordData.Open sql, conn, adOpenForwardOnly, adLockReadOnly, adCmdText
Else
Set recordData = Nothing
End If
Set GetRecords = recordData
recordData.Close
End Function
如果我重命名或删除它当前停止的文件,它会在新的第65个文件上出错,所以我知道实际的文件本身不应该受到责备。我可以在一个会话中打开的记录集数量是否有限制,或者我是否以低效的方式打开它们?
答案 0 :(得分:1)
嗯,在修补它之后,我发现问题在于连接。我没有将连接字符串构造为字符串,而是创建了一个连接对象,然后在打开记录集后将其关闭。必须对给定会话中可存在的连接数量进行某种限制。这是修订后的功能:
Public Function GetRecords(ByVal dataSrc as String) as ADODB.Recordset
Dim dir as String
Dim file as String
Dim recordData as ADODB.Recordset
Dim sql as String
Dim cn as ADODB.Connection
dir = "C:\MyDirectory"
file = dataSrc & ".csv"
If DoesFileExist(dir & file) Then
sql = "select * from " & file & ";"
Set recordData = New ADODB.Recordset
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & dir & ";" & "Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;"""
.CursorLocation = adUseClient
.Open
End With
recordData.CursorLocation = adUseClient
recordData.Open sql, conn, adOpenForwardOnly, adLockReadOnly, adCmdText
cn.Close
Else
Set recordData = Nothing
End If
Set GetRecords = recordData
recordData.Close
End Function