Excel:从一个工作簿中提取列以附加到另一个工作簿

时间:2011-07-11 07:27:32

标签: excel excel-vba vba

我遇到这样的问题: 我有多个工作簿与数据共享相同的模板:(假设它们被命名为“1.xlsx”,“2.xlsx”......) A2:文件#(例如:在“”1.xlsx“中它是”File1“) Field1 Field2 Field3 Field4(存储在D3:G40中的数据)

我有一个文件名“Full.xlsx” 文件#Field1 Field2

现在我需要将数据D3:E40从“1.xlsx”,“2.xlsx”...复制到“Full.xlsx”的Sheet1(Field1,Field2),并将它们的A2转到文件#

例如,我有:

1.xlsx:
[A2] File1
[D2]Field1 [E2]Field2 [F2]Field3 [G2]Field4
[D3]aa [E3]bb [F3]cc [G3]dd
[D4]ee [E4]ff [F4]gg [G4]hh
...

2.xlsx:
[A2] File2
Field1 Field2 Field3 Field4
11 22 33 44
55 66 77 88
...

I need to have sheet1 in "Full.xlsx":

[A1]File# [B1]Filed1 [C1]Filed2
[A2]File1 [B2]aa [C2]bb
[A3]File1 [B3]ee [C3]ff
...
[A40]File2 [B40]11 [C40]22
[A41]File2 [B41]55 [C41]66
...

有人可以告诉我怎么做吗? (我正在使用MS Excel 2010)

更新:我终于写了一些有用的东西(我是VBA的新手,所以它可能不是最好的解决方案)

Public Sub copyrows()
Dim FileNum As String
Dim LastRow As Long, i As Long, Counter As Integer
Dim Dest As Workbook
Set Dest = Workbooks("Full.xlsm")

FileNum = Cells(2, 1).Value

Dest.Activate

LastRow = Dest.Worksheets("Sheet1").Range("C65536").End(xlUp).Row + 1
i = LastRow

For Counter = 3 To 40
    Dest.Worksheets("Sheet1").Cells(i, 1).Value = FileNum
    i = i + 1
Next

ThisWorkbook.Activate
ThisWorkbook.Worksheets("Sheet1").Range("D3", "E40").Copy
Dest.Activate
Dest.Worksheets("Sheet1").Range("B" & LastRow, "C" & i).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False
End Sub

感谢大家的关注!

1 个答案:

答案 0 :(得分:0)

您可以使用搜索框查看周围发生的事情: - How can I copy columns from one sheet to another with VBA in Excel? - Copy data from one sheet to another using VBA - Excel Copy Worksheet from external WorkBook

顺便说一句,您可以在当前页面的右栏找到许多相关帖子。

然而,如果您需要帮助,请发布您已构建的代码,以便我们可以帮助您改进或调试它。