Public Function Import_CSV (SheetName) As String
Dim ws As Worksheet, strFile As String
Set ws = ActiveWorkbook.Sheets(SheetName) 'set to current worksheet name
strFile = Application.GetOpenFilename("CSV Files (*.csv),*.csv", , "Please selec .csv file...")
Dim wbkS As Workbook
Dim wshS As Worksheet
Dim wshT As Worksheet
Set wbkS = Workbooks.Open(Filename:=strFile)
Set wshS = wbkS.Worksheets(1)
LastRow = wshS.UsedRange.Rows.Count
LastCol = wshS.UsedRange.Columns.Count
With ws
For i = 1 To LastRow Step 1
For j = 1 To LastCol Step 1
.Cells(i, j).Value = wshS.Cells(i, j)
Next
Next
End With
wbkS.Close
ActiveWorkbook.Save
End Function
我尝试使用上面的代码将.csv文件中的数据复制到excel表。但我的csv文件很大(2000行和2000列)。它花了很多时间。有没有其他方法我可以没有太多时间将数据复制到excel。
请帮我解决这个问题。
答案 0 :(得分:0)
如果需要将值从一个工作表复制到另一个工作表但保存目标工作表的格式,则可以将整个值数组从源范围分配到目标范围。
示例:
Sub test()
Set ws = Worksheets(2)
Set wshS = Worksheets(1)
LastRow = 2000
LastCol = 2000
ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, LastCol)).Value = wshS.Range(wshS.Cells(1, 1), wshS.Cells(LastRow, LastCol)).Value
End Sub
有了这个,你可能会遇到非常大的数组的内存问题。
或者您可以使用剪贴板,然后仅粘贴特殊值。
示例:
Sub test2()
Set ws = Worksheets(2)
Set wshS = Worksheets(1)
LastRow = 2000
LastCol = 2000
wshS.Range(wshS.Cells(1, 1), wshS.Cells(LastRow, LastCol)).Copy
ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, LastCol)).PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub
这对我来说更快,但这可能是一种主观印象。