我必须将多个excel合并到单个excel工作簿中。假设我有3张excel表。
ExcelA.xls - 它包含3列A,B,C
ExcelB.xls - 它包含4列B,D,E,F
ExcelC.xls - 它包含3列A,C,D
现在我的ExcelFinal.xls应该包含A,B,C,D,E,F总是,对列的数据映射应始终保持不变。 列名也不应该在行中重复。我们需要使用VB脚本来实现这一点。
快速的帮助将受到高度赞赏!
谢谢! 阿洛克
答案 0 :(得分:0)
Sub CopyData()
Dim sourceColumn As Range, targetColumn As Range
Dim columnValues, sourceWorksheet, sourceWorkbook, targetWorkheet, targetWorkbook As String
Dim currentWorkbook, templateWorksheet, reference As String
sourceWorkbook = "Data.xlsx"
sourceWorksheet = "data"
targetWorkbook = "DynamicColumnsTemplate.xlsm"
targetWorkheet = "data"
templateWorksheet = "template"
' For 1st column
Set currentWorkbook = Workbooks(targetWorkbook)
currentWorkbook.Sheets(templateWorksheet).Activate
reference = "A4"
columnValues = Range(reference).value
If columnValues <> " " Then
Set sourceColumn = Workbooks("Data.xlsx").Worksheets(1).Columns(columnValues)
Set targetColumn = Workbooks("DynamicColumnsTemplate.xlsm").Worksheets("data").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End If
' For 2nd column
Set currentWorkbook = Workbooks(targetWorkbook)
currentWorkbook.Sheets(templateWorksheet).Activate
reference = "B4"
columnValues = Range(reference).value
If columnValues <> " " Then
Set sourceColumn = Workbooks("Data.xlsx").Worksheets(1).Columns(columnValues)
Set targetColumn = Workbooks("DynamicColumnsTemplate.xlsm").Worksheets("data").Columns("B")
sourceColumn.Copy Destination:=targetColumn
End If
' For 3rd column
Set currentWorkbook = Workbooks(targetWorkbook)
currentWorkbook.Sheets(templateWorksheet).Activate
reference = "C4"
columnValues = Range(reference).value
If columnValues <> " " Then
Set sourceColumn = Workbooks("Data.xlsx").Worksheets(1).Columns(columnValues)
Set targetColumn = Workbooks("DynamicColumnsTemplate.xlsm").Worksheets("data").Columns("C")
sourceColumn.Copy Destination:=targetColumn
End If
' For 4th column
Set currentWorkbook = Workbooks(targetWorkbook)
currentWorkbook.Sheets(templateWorksheet).Activate
reference = "D4"
columnValues = Range(reference).value
If columnValues <> " " Then
Set sourceColumn = Workbooks("Data.xlsx").Worksheets(1).Columns(columnValues)
Set targetColumn = Workbooks("DynamicColumnsTemplate.xlsm").Worksheets("data").Columns("D")
sourceColumn.Copy Destination:=targetColumn
End If
' For 5th column
Set currentWorkbook = Workbooks(targetWorkbook)
currentWorkbook.Sheets(templateWorksheet).Activate
reference = "E4"
columnValues = Range(reference).value
If columnValues <> " " Then
Set sourceColumn = Workbooks("Data.xlsx").Worksheets(1).Columns(columnValues)
Set targetColumn = Workbooks("DynamicColumnsTemplate.xlsm").Worksheets("data").Columns("E")
sourceColumn.Copy Destination:=targetColumn
End If
End Sub