我正在使用Excel VBA代码通过ADODB连接连接到CSV文件(24,179,689行)。宏运行并通过一列上的特定过滤器从excel获取数据。使用我现在正在尝试的过滤器,它应该返回大约1500行数据。
我已经通过在其他地方手动加载CSV进行了检查,并且数据实际上在那里。但是,当我使用ADODB连接时,我的记录集仍然为空。
我做了一些额外的测试:完整的CSV文件上的count(*),在那里我看到了错误:它只返回155,535行。因此,我要应用的特定过滤器可能不在该数据中,因此它返回0行。
这是我的代码:
Public adoConn As ADODB.Connection
Public adoRS As ADODB.Recordset
Sub getdata()
Set adoConn = New ADODB.Connection
Set adoRS = New ADODB.Recordset
Dim rawFile As String
Dim strSQL As String
'The xlsx file to treat as a database
rawFile = "myPathName"
'Open a connection to the workbook
sconnect = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" & rawFile & ";Extended Properties='text;HDR=YES;FMT=Delimited'"
'Write the SQL necessary to get the data you want
sql2 = "SELECT count(*) from [MyFileName.csv]"
'Now we open up our recordset using the connection and the sql statement
adoRS.Open sql2, adoConn, adOpenStatic
Debug.Print (adoRS.EOF)
'Last, we dump the results in this viz sheet
Blad1.Range("A1").CopyFromRecordset adoRS
adoRS.Close
adoConn.Close
End Sub
因此,它返回155,535。
我也尝试过通过创建ADODB命令而不使用上述连接。或连接超时。没有结果。
这是内存问题还是其他?如何解决?
请尝试一下,看看它是否满足您的要求。另外,设置对Microsoft ActiveX数据对象2.8库的引用。
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = "C:\your_path_here\"
sconnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPath & ";Extended Properties='text;HDR=YES;FMT=Delimited'"
Conn.Open sconnect
sSQLSting = "SELECT * From CSV1.csv WHERE ID = 2"
mrs.Open sSQLSting, Conn
ActiveSheet.Range("A2").CopyFromRecordset mrs
'Close Recordset
mrs.Close
Conn.Close
我的CSV看起来像这样。
我的CSV行超过一百万;我不能放入2300万行!无论如何,在我的测试中,只有一百万多行,我在大约1秒钟内得到了我期望的准确结果,并且我的计算机是超级超级超级超级慢!!