我有700个CSV文件,每个文件有7列1000行,我需要把它们合并成一个长列。示例代码可以进行复制,但我不知道如何在复制之前创建一列(与该文件中的其他列长度相同),并将每个单元格中的工作表或文件名添加到该列中。如果可能的话,我只需要从每个CSV文件中获取A列(日期)、创建的列(工作表名称)和F列(值),顺序为A、创建的列和F。
Sub ImportData()
Dim lastrow As Long
Dim clastrow As Long
Dim filePath As String
Dim fileName As String
Dim count As Long
Dim importRange As Range
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim cws As Excel.Worksheet
count = 0
Set cws = ThisWorkbook.Sheets(2)
filePath = "C:\Users\user\Desktop\CSV files\"
fileName = Dir(filePath & "*.csv")
Do While fileName <> ""
count = count + 1
Set wb = Excel.Workbooks.Open(filePath & fileName)
Set ws = wb.Worksheets(1)
lastrow = ws.Cells(Rows.count, "a").End(xlUp).Row
clastrow = cws.Cells(Rows.count, "a").End(xlUp).Row + 1
Set importRange = ws.Range("a2:f" & lastrow) 'skips header row
' cws.Cells(clastrow, 1).End(xlUp).Offset(1, 0).Resize(importRange.Rows.count, importRange.Columns.count) = importRange.Value
importRange.Copy
cws.Cells(clastrow, "a").PasteSpecial xlPasteValues
wb.Application.CutCopyMode = False
wb.Close
fileName = Dir
Loop
End Sub