excel 将工作表从关闭的工作簿复制并覆盖到另一个关闭的工作簿

r7s23pms  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(144)

一个初学者在这里需要帮助。我有4个excel文件。excel 1有sheetname report 1。excel 2有sheetname report 2。excel 3(我的主要报告excel文件)。excel 4(我的跟踪excel文件)。
Excel编号1,2,3已关闭,只有Excel 4打开。我想做一个VBA脚本,如果单击Excel 4按钮,将复制/覆盖sheetnames(report 1和report 2)到Excel 3(我的主报告Excel文件)。真的很感激,如果有人可以帮助/指导我如何启动代码或请分享,如果已经VBA脚本几乎类似。谢谢。

erhoui1w

erhoui1w1#

看看这个

Sub CopySheets()
    
    With Application
    
        .ScreenUpdating = False
        .EnableEvents = False
        .DisplayAlerts = False
        .Calculation = xlCalculationManual
    
    End With
    
    'Path for Excel3 file
    Dim strFilename3 As String: strFilename3 = "E:\SO1\Excel3.xlsx"
    
    Set wb3 = Workbooks.Open(Filename:=strFilename3)
    
    'Path for Excel1 file
    Dim strFilename1 As String: strFilename1 = "E:\SO1\Excel1.xlsx"
    
    Set wb1 = Workbooks.Open(Filename:=strFilename1)
    
    'Each worksheet in a workbook
    For Each ws1 In wb1.Worksheets
        
        If ws1.Name = "report1" Then
            
            'copy sheet name to a variable
            'str1 = ws1.Name
            ws1.Copy Before:=Workbooks("Excel3.xlsx").Sheets(1)
            
        End If
    
    Next ws1
    
    wb1.Close SaveChanges:=False
    
    'Path for Excel2 file
    Dim strFilename2 As String: strFilename2 = "E:\SO1\Excel2.xlsx"
    
    Set wb2 = Workbooks.Open(Filename:=strFilename2)
    
    'Each worksheet in a workbook
    For Each ws2 In wb2.Worksheets
        
        If ws2.Name = "report2" Then
            
            'copy sheet name to a variable
            'str2 = ws2.Name
            ws2.Copy Before:=Workbooks("Excel3.xlsx").Sheets(1)
            
            
        End If
    
    Next ws2
    
    wb2.Close SaveChanges:=False
    
    wb3.Close SaveChanges:=True
    
    
    With Application
    
        .ScreenUpdating = True
        .EnableEvents = True
        .DisplayAlerts = True
        .Calculation = xlCalculationAutomatic
    
    End With

    MsgBox ("Completed")
    
End Sub

相关问题