excel - 根据主文件中的单元格值将多个文件中的数据复制到主文件

标签 excel vba

这里是第一次海报。

我有一个文件列表(file1file2file3),我想将这些文件中的一个范围复制到主文件中文件。主文件包含一个包含以下数据的列:file1file2file3。如何循环遍历该列并将每个文件的范围复制并粘贴到母版中的相应行中?我需要将 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/

相关文章:

vba - 如何获得一个函数来引用它所在的单元格?

vba - 从变量起始行向下填充

vba - 使用 VBA 将范围作为公式中的参数传递

vba - 对于 VBA 中的每个循环意外地跳过行

ms-access - 如何锁定 Access 子表单中的记录

regex - 如果相邻单词以相同字母开头,则将空格替换为 "/",否则 "&"Excel 宏 VBA

excel - 声明公共(public)变量并赋值 - VBA

excel - VBA - 从合并单元格单击/到是/否时更改单元格值

excel - 以波浪号分隔导出

VBA - 查找重复并比较其中哪一个是最高的