Forum Discussion

MixMasterMike's avatar
MixMasterMike
Copper Contributor
Jan 15, 2023
Solved

Open and close source workbooks based on cell values in a Master Workbook

I am developing a macro that copies sheets from multiple different workbooks and pastes them into individual sheets into a Master workbook. I want the macro to close the source workbook(s) after copy...
  • HansVogelaar's avatar
    HansVogelaar
    Jan 16, 2023

    MixMasterMike 

    Sub Get_Source_Data()
        Dim FolderPath As String, Filename As String
        Dim wbkSource As Workbook, wbkTarget As Workbook
        Dim wshNames As Worksheet, wshTarget As Worksheet
        Dim r As Long
    
        Application.ScreenUpdating = False
        Set wbkTarget = Workbooks("2023-24 Master Budget.xlsm") ' or Thisworkbook
        Set wshNames = wbkTarget.Worksheets("Names") ' change as needed!
        r = 10
        Do
            FolderPath = wshNames.Range("F" & r).Value
            If Right(FolderPath, 1) <> "\" Then
                FolderPath = FolderPath & "\"
            End If
            Filename = wshNames.Range("C" & r).Value
            Set wbkSource = Workbooks.Open(FolderPath & Filename)
            Set wshTarget = wbkTarget.Worksheets(wshNames.Range("D" & r).Value)
            wbkSource.Worksheets("4.1 Operating").Cells.Copy Destination:=wshTarget.Range("A1")
            wbkSource.Close SaveChanges:=False
            r = r + 1
        Loop Until wshNames.Range("C" & r).Value = ""
        Application.ScreenUpdating = True
    End Sub

Resources