我长期以来一直是StackOverflow的忠实读者和钦佩者。
基本上,我正在尝试循环遍历一系列Excel文件,将一定范围的数据复制并粘贴到单个Excel工作簿/工作表中。
单元格范围位置(C3:D8,D3:E8)不总是一致的,但表格维度为:29R x 2C。此外,这些文件只有1个工作表,在指定的表格维度之外没有其他单元格数据值。
目前的代码正在执行,但没有将任何内容粘贴到其目标Excel文件中。
我需要它:
- 查找文件中的数据维度(表格)
- 复制该表格
- 粘贴到目标位置(在上一个表格下方)
- 循环到下一个文件
- 重复步骤1-4
代码来源于: Excel VBA: automating copying ranges from different workbooks into one final destination sheet?
非常感谢您的帮助,如果我的问题含糊不清,请告诉我需要澄清的内容。
Sub SourcetoDest()
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sDestPath As String
Dim sSourcePath As String
Dim shDest As Worksheet
Dim rDest As Range
Dim vaFiles As Variant
Dim i As Long
'array of folder names under sDestPath
'array of file names under vaFiles
vaFiles = Array("Book1.xls")
sDestPath = "C:\Users"
sSourcePath = "C:\Users"
Set wbDest = Workbooks.Open(sDestPath & "\" & "Book2.xlsm")
Set shDest = wbDest.Sheets(1)
'loop through the files
For i = LBound(vaFiles) To UBound(vaFiles)
'open the source
Set wbSource = Workbooks.Open(sSourcePath & "\" & vaFiles(i))
'find the next cell in col C
Set rDest = shDest.Cells(shDest.Rows.Count, 3).End(xlUp).Offset(1, 0)
'write the values from source into destination
rDest.Resize(5, 1).Value = wbSource.Sheets(1).Range("C7:D33").Value
wbSource.Close False
Next i
End Sub
End()
函数)。但我不明白为什么目标工作表中没有任何数据... - R3uKrDest.Resize(5, 1).Value = wbSource.Sheets(1).Range("C7:D33").Value
行之前尝试使用wbSource.Sheets(1).Range("C7:D33").Select
,它将突出显示源数据。使用 F8 逐步执行代码并检查源范围是否正确。接下来尝试使用rDest.Resize(5, 1).Select
检查目标范围。一旦这些都正确,您可以在完成调试后删除这两行。 - tonester640