excel - VBA将多个工作簿中的单元格复制到另一个工作表中
问题描述
我在同一个文件夹中有 10 个 excel 文件。我正在尝试将活动工作表的单元格 A2 从这 10 个 excel 文件中的每一个复制到另一个 excel 文件的工作表中 - 我们称之为 EX2 文件。EX2 有一个工作表名称产品,我想在此工作表的 A 列末尾有新的 10 个值。
下面是我的代码。我已经尝试了多次,但没有奏效
Dim Path As String
Dim Filename As String
Dim WB As Workbook
Dim RowCnt As Long
Path = "C:\Users\***\Documents\Folder 10\"
Filename = Dir(Path & "*.xlsm*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While Filename <> ""
Set WB = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
For Each ActiveSheet In WB.Sheets
ActiveSheet.Cells(2, 1).Copy
RowCnt = ThisWorkbook.Worksheets("Product").Range("A1").End(xlDown).Row + 1
ThisWorkbook.Worksheets("Product").Range("A" & RowCnt).PasteSpecial xlPasteValues
Next ActiveSheet
WB.Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
解决方案
复制单元格
Option Explicit
Sub copyCell()
Const FolderPath = "C:\Users\***\Documents\Folder 10\"
Dim Filename As String: Filename = Dir(FolderPath & "*.xlsm")
Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets("Product")
Dim dCell As Range: Set dCell = dws.Cells(dws.Rows.Count, "A").End(xlUp)
Application.ScreenUpdating = False
Do While Filename <> ""
Set dCell = dCell.Offset(1)
With Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
dCell.Value = .ActiveSheet.Range("A2").Value
.Close False
End With
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
推荐阅读
- php - 没有在 Heroku WordPress 中添加新插件的选项
- ssl - 通过 SSH 在 WHM 中安装 SSH 证书
- php - PHP 删除重复数组值的最佳性能
- c# - WPF 直接绑定到 DataContext
- c++ - 从单例到嵌套侦听器没有可行的转换 *
- pytorch - Pytorch nn.embedding 错误
- python - 避免迭代太多时间 - 算法构建
- node.js - SyntaxError:在安装 SASS 节点包的严格模式之外尚不支持块范围的声明(let、const、函数、类)
- asp.net - 无法将文本框值返回到条件检查输入字符串的格式不正确
- rating - 产品标题下的星级评分错误