是否可以并排合并excel文件。假设我在驱动器C中存储了两个单独的Excel文件,名为A和B,例如文件A是这样的:
BB LL KO PO
A C D A
A C D A
A C D A
A C D A
文件B如:
WW YY ZZ XX
Q C D Z
Q C D Z
Q C D Z
Q C D Z
我需要这个:
BB LL KO PO WW YY ZZ XX
A C D A Q C D Z
A C D A Q C D Z
A C D A Q C D Z
A C D A Q C D Z
由于
答案 0 :(得分:0)
我假设表格从单元格A1(表格的左上角单元格)开始,并且您有4x4表格(您可以轻松地概括该行为)。您必须在工作表中运行此代码,您希望合并数据。您还必须在代码中指定文件的路径,并确保工作表的名称正确无误。
Sub merge()
Dim actWb, wb As Workbook
Dim i, j As Integer
'set workbooks, so you can switch between them during the program
Set actWb = Application.ActiveWorkbook
'here you also open workbook you want to copy data from
Set wb = Workbooks.Open("PATH TO THE FILE")
'loop through the range you want to copy
For i = 1 To 4
For j = 1 To 4
actWb.Sheets("Sheets1").Cells(i, j).Value = wb.Sheets("Sheets1").Cells(i, j).Value
Next j
Next i
'close the workbook
wb.Close
'repeat above for the other workbook
Set wb = Workbooks.Open("PATH TO THE OTHER FILE")
For i = 1 To 4
For j = 1 To 4
actWb.Sheets("Sheets1").Cells(i, j + 4).Value = wb.Sheets("Sheets1").Cells(i, j).Value
Next j
Next i
wb.Close
End Sub
希望有所帮助:)
答案 1 :(得分:0)
您可以使用Function
来处理Variant
变量中给定工作簿的给定工作表的单元格值,如下所示:
Function GetWBValues(fullFileName As String, shtName As String, values As Variant) As Boolean
On Error GoTo ExitFunction
With Workbooks.Open(fullFileName).Worksheets(shtName) '<--| try opening passed file and accessing its passed sheet name
values = .UsedRange.Value
.Parent.Close False '<--| close just opened workbook without saving any changes
End With
GetWBValues = True '<--| set function return value to 'True' to signal calling sub that values has been successfully read
ExitFunction:
End Function
被一些“主要”调用代码利用,如下所示:
Option Explicit
Sub merge()
Dim values As Variant
If GetWBValues("C:\Desktop\......\File1.xlsx", "Sheet1", values) Then
Cells.Resize(UBound(values, 1), UBound(values, 2)).Value = values
End If
If GetWBValues("C:\Desktop\......\File2.xlsx", "Sheet4", values) Then
With ActiveSheet.UsedRange
.Columns(.Columns.Count + 1).Resize(UBound(values, 1), UBound(values, 2)).Value = values
End With
End If
End Sub