VBA来实现跨工作簿的批量复制粘贴

前言        

        不破坏源数据,只把源数据引用到其它文件,再开始计算.

        技术没有老旧之分,有时VBA的技能,会因为使用的方便,也能快速实现需求.

代码

Sub CopyPasteData()
    Dim sourceWorkbook As Workbook
    Dim destinationWorkbook As Workbook
    Dim sourceWorksheet As Worksheet
    Dim destinationWorksheet As Worksheet
    
    ' 设置源工作簿和目标工作簿
    Set sourceWorkbook = Workbooks.Open("C:\路径\源工作簿.xlsx")
    Set destinationWorkbook = Workbooks.Open("C:\路径\目标工作簿.xlsx")
    
    ' 设置源和目标工作表
    Set sourceWorksheet = sourceWorkbook.Worksheets("Sheet1")
    Set destinationWorksheet = destinationWorkbook.Worksheets("Sheet1")
    
    ' 定义源和目标区域
    Dim sourceRange As Range
    Dim destinationRange As Range
    
    Set sourceRange = sourceWorksheet.Range("A1:B10") ' 源范围
    Set destinationRange = destinationWorksheet.Range("A1") ' 目标范围
    
    ' 复制和粘贴数据
    sourceRange.Copy destinationRange
    
    ' 关闭工作簿,保存更改
    sourceWorkbook.Close SaveChanges:=False
    destinationWorkbook.Close SaveChanges:=True
    
    ' 清除对象引用
    Set sourceRange = Nothing
    Set destinationRange = Nothing
    Set sourceWorksheet = Nothing
    Set destinationWorksheet = Nothing
    Set sourceWorkbook = Nothing
    Set destinationWorkbook = Nothing
    
End Sub

你可能感兴趣的:(excel)