这里是第一次海报。
我有一个文件列表(file1
、file2
、file3
),我想将这些文件中的一个范围复制到主文件中文件。主文件包含一个包含以下数据的列:file1
、file2
、file3
。如何循环遍历该列并将每个文件的范围复制并粘贴到母版中的相应行中?我需要将 file1
中的数据放入与 file1
同一行的范围内。
这是我到目前为止所拥有的:
Dim col As Range
Dim cell As Range
Dim currentRow As Long
Dim varCellValue As String
Dim pasteRangeC As String
Dim pasteRangeE As String
Set col = Range("B3:B5")
currentRow = 3
For Each cell In col
varCellValue = cell.Value
currentRow = 3
pasteRangeC = "C" & currentRow
pasteRangeE = "E" & currentRow
'## Open workbooks:
Set x = Workbooks.Open("C:\Folder\" & varCellValue &_ ".xlsx")
Set y = ThisWorkbook
'Copy from x:
x.Sheets("Summary").Range("D13:F13").Copy
'Paste to y worksheet:
y.Sheets("Sheet1").Range(pasteRangeC & ":" & pasteRangeE).PasteSpecial xlPasteValues
'Close x:
x.Close
currentRow = currentRow + 1
Next
End Sub
该代码适用于第一个循环,然后出现运行时错误 1004,无法找到该文件。所以我认为 varCellValue 没有获取下一个单元格的值。
有人能指出我正确的方向吗?
最佳答案
根据我读到的内容,尝试以下操作
Option Explicit 'Use every time will keep you from making simple mistakes...
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim wbSource As Workbook
Dim i As Integer
On Error GoTo ErrCatch 'add to catch errors
Set wb = Application.ThisWorkbook
Set ws = wb.Worksheets("Sheet1")
For i = 1 To 5
'## Open workbooks:
Set wbSource = Workbooks.Open("C:\Folder\" & ws.Cells(i, 2).Value & ".xlsx") 'Cells(Row,Column) 2 = "B"
'Copy from wbSource and paste in worksheet
wbSource.Sheets("Summary").Range("D13:F13").Copy Destination:=ws.Cells(i, 3) 'This syntax keeps you from having to do "Application.CutCopyMode = False" to remove the marching ants.
'Close source:
wbSource.Close False
Next i
ErrCatch:
If Err.Number > 1 Then 'test if an error was thrown
MsgBox "Error Number: " & Err.Number & vbCrLf & _
"Error Description: " & Err.Description, vbCritical
End If
End Sub
关于excel - 根据主文件中的单元格值将多个文件中的数据复制到主文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34025680/