我有一个 53 个变量、7.9MM 行的 CSV 文件要导入到 Excel 中。这超出了 Excel 的行限制。我想将 CSV 中的一组 8 个文件(每个文件包含大约 100 万行)导入到 Excel 中。使用 Excel,如何将行的导入子集化为 100 万条记录,每条记录最终将所有数据从 Csv 导入到 Excel 中?基本文件包含命名列的标题行。
我曾经在Excel中导入功能,达到了行数限制。
我要求ChatGPT3.5编写导入子集的代码,以下是我尝试使用的:
Sub ImportCSVSubset()
Dim CSVFilePath As String
Dim ws As Worksheet
Dim startRow As Long
Dim endRow As Long
Dim i As Long
' Define the CSV file path
CSVFilePath = "C:\Users\mmcbu\Desktop\GAVR\GAVRdata\GAVR.csv"
' Define the worksheet to import the data
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your desired sheet name
' Define the range of rows to import
startRow = 1 ' Start importing from row 2
endRow = 1000 ' Import until row X, change as needed
' Clear existing data in the worksheet
ws.UsedRange.Clear
' Open the CSV file and read the data
With ws.QueryTables.Add(Connection:="TEXT;" & CSVFilePath, Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True ' CSV files are typically comma-delimited
.TextFileStartRow = 1
.TextFileColumnDataTypes = Array(1) ' Array(1) for all text data
.Refresh BackgroundQuery:=False
End With
' Delete extra rows if the imported data exceeds the specified range
If ws.Cells(ws.Rows.Count, 1).End(xlUp).Row > endRow Then
ws.Range(ws.Cells(endRow + 1, 1), ws.Cells(ws.Rows.Count, 1)).EntireRow.Delete
End If
' Delete rows above the specified range
If startRow > 1 Then
ws.Rows("1:" & startRow - 1).Delete
End If
' Adjust column widths
ws.Columns.AutoFit
MsgBox "CSV data imported successfully!", vbInformation
End Sub
此代码正确导入 1,048,576 行。但是,我只请求了 1000 行。关于如何将行数限制为请求的限制有什么建议吗?
无论您有一个包含 790 万行的 CSV 文件还是 8 个每个约 100 万行的 CSV 文件,您都可以使用 Power Query 从该单个文件中获取数据,或者通过从文件夹导入来指定多个文件。
如果需要显示数据,请使用 Power Query 进行子集化,将它们拆分为每个约 100 万行的单独表,然后加载表,这将自动从每个表创建一个新工作表。
但是,如果您需要加载数据以最终使用数据透视表进行分析,则可以加载为“仅创建连接”。这不会填充数据,但会保持与 CSV 文件的连接以执行分析。