VBA 从一个Excel文件 表头相同数据复制到另一个Excel表头相同文件中
时间: 2023-11-22 21:56:47 浏览: 325
你可以使用以下代码来复制数据:
```
Sub CopyData()
Dim sourceWorkbook As Workbook
Dim destinationWorkbook As Workbook
Dim sourceWorksheet As Worksheet
Dim destinationWorksheet As Worksheet
Dim sourceRange As Range
Dim destinationRange As Range
'打开源工作簿和目标工作簿
Set sourceWorkbook = Workbooks.Open("sourceWorkbook.xlsx")
Set destinationWorkbook = Workbooks.Open("destinationWorkbook.xlsx")
'设置源工作表和目标工作表
Set sourceWorksheet = sourceWorkbook.Worksheets("Sheet1")
Set destinationWorksheet = destinationWorkbook.Worksheets("Sheet1")
'设置源范围和目标范围
Set sourceRange = sourceWorksheet.Range("A1").CurrentRegion
Set destinationRange = destinationWorksheet.Range("A1").CurrentRegion
'复制数据
sourceRange.Copy Destination:=destinationRange
'关闭工作簿
sourceWorkbook.Close SaveChanges:=False
destinationWorkbook.Close SaveChanges:=True
Set sourceWorkbook = Nothing
Set destinationWorkbook = Nothing
Set sourceWorksheet = Nothing
Set destinationWorksheet = Nothing
Set sourceRange = Nothing
Set destinationRange = Nothing
End Sub
```
你需要将代码中的 "sourceWorkbook.xlsx" 和 "destinationWorkbook.xlsx" 替换为实际的文件名,并将源工作表和目标工作表的名称替换为实际的名称。此代码假设源文件和目标文件中的工作表都名为 "Sheet1",并且表头相同。
阅读全文