我试图将一个大的.csv文件导入到Excel中。该文件有近400万行和329列,因此它远远超过了Excel的 1M行限制。我在网上找到一个VB脚本来将文本文件导入到Excel中,一旦超出行限制,脚本将创建一个新的工作表,直到所有工作表中的总行数等于原始文本文件中的总行数。将一个大的.csv文件导入到Excel中,
Sub ImportLargeFile()
'Imports text file into Excel workbook using ADO.
'If the number of records exceeds 65536 then it splits it over more than one sheet.
Dim strFilePath As String, strFilename As String, strFullPath As String
Dim lngCounter As Long
Dim oConn As Object, oRS As Object, oFSObj As Object
'Get a text file name
strFullPath = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please select text file...")
If strFullPath = "False" Then Exit Sub 'User pressed Cancel on the open file dialog
'This gives us a full path name e.g. C:\temp\folder\file.txt
'We need to split this into path and file name
Set oFSObj = CreateObject("SCRIPTING.FILESYSTEMOBJECT")
strFilePath = oFSObj.GetFile(strFullPath).ParentFolder.Path
strFilename = oFSObj.GetFile(strFullPath).Name
'Open an ADO connection to the folder specified
Set oConn = CreateObject("ADODB.CONNECTION")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFilePath & ";" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"""
Set oRS = CreateObject("ADODB.RECORDSET")
'Now actually open the text file and import into Excel
oRS.Open "SELECT * FROM " & strFilename, oConn, 3, 1, 1
While Not oRS.EOF
Sheets.Add
ActiveSheet.Range("A1").CopyFromRecordset oRS, 65536
Wend
oRS.Close
oConn.Close
End Sub
然而,当我在Excel 2007中运行它,我得到以下错误:
Run-time error '-2147217900 (80040e14)':
Syntax error in FROM clause.
在点击调试它指向此行
oRS.Open "SELECT * FROM " & strFilename, oConn, 3, 1, 1
我有不存在的VB技能,任何帮助在这里将不胜感激。
谢谢!
编辑:我发现这个http://support.microsoft.com/kb/193514但这在这种情况下不起作用,事实上我甚至不知道在哪里放置方括号。任何放置括号的地方,Excel都拒绝给出运行选项。
编辑2:我试着在不同的机器上运行它,它只是有更多的汁液,使内存不成问题。这台电脑也有它的Office 2013(尽管它没有Office 365)。我运行了同样的宏,它给出了以下错误。
Run-time error '3706':
Provider cannot be found. It may not be properly installed.
当我点击调试它指向此行
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFilePath & ";" & _
-> "Extended Properties=""text;HDR=Yes;FMT=Delimited"""
我不知道VBA要么,但'SELECT'部分是SQL,我的理解多一点。你能否包含你的csv的头文件和你有vba脚本的地方? – Jerry 2013-05-14 15:58:54
标题与列不同吗?原谅我,如果我听起来很呆板,但VB对我来说确实是完全陌生的。 – user2382345 2013-05-14 16:17:24
不,不,问得很好。通过标题,我的意思是你的csv中的列名,如果你有它们的话。您提供的MS支持链接提到您导入的文件中包含短划线的列标题/名称会导致此错误。相反,如果你知道如何使用它并导出更小的文件到excel,你可以在MS访问中导入文件。但是在到达那里之前,我想看看你在哪里得到这个vba脚本,也许这里有一些指导。 – Jerry 2013-05-14 16:30:56