首页 > 解决方案 > 将多个 .csv 文件导入单个电子表格

问题描述

我正在开发一个简单的宏,以从文件夹中获取所有 csv 文件并将数据复制到单个工作表中。所有 csv 文件的格式都与标题相同,并且在 a:f 列中使用了数据。宏将依次打开每个文件,但不会复制任何内容。我也尝试绕过复制/粘贴,但仍然一无所获。有任何想法吗??

Option Explicit

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("Raw_Data")

filePath = "C:\Users\christopher.huiett\Desktop\csv_folder\"
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" & 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

标签: excelvbacsvimport

解决方案


我认为你的问题是线路Set importRange = ws.Range("a2" & lastrow)。考虑 lastrow = 1000:您可以将 importRange 设置为A21000- 一个肯定为空的单元格。

虽然UsedRange当您想弄清楚有多少行/列正在使用时,使用通常不是选择的方法:打开工作簿时,它是可靠的。你想跳过第一行,所以你可以简单地使用 use UsedRange.Offset(1, 0)。这将在末尾复制一个空行,但这没有害处。

clastrow = cws.Cells(ws.Rows.count, "a").End(xlUp).Row + 1
Set importRange = ws.UsedRange.Offset(1, 0)

推荐阅读