excel - 将多个 .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
解决方案
我认为你的问题是线路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)
推荐阅读
- php - 将 foreach 循环之外的数组值动态加载到电子邮件中
- python - 无法让我的图表使用来自 mongoDB 的数据
- android - 我有一个膨胀类 android.support.design.widget.BottomNavigationView 错误。有什么想法吗?
- javascript - 应该如何声明一个空的时间戳变量,以便成为一个全局变量,以便我们稍后给它一个值?
- java - Jaxb2-maven-plugin 错误 java11 schema_reference
- amazon-web-services - 如何将 AWS 聊天机器人集成到网站中?
- c++ - 将 shared_ptr 与 CArray 一起使用?
- excel - 无限循环用文本替换空格
- angular - 禁用菜单导航项
- qt - 在 QToolTip 中设置图像时删除边距