Option Explicit
Option Compare Text
Sub CopyData()
'=============================================
' Loop through the list of workbook names
' and copy data into this workbook
'=============================================
Dim WB As Workbook 'This workbook
Dim LST As Worksheet 'This workbook
Dim xWB As Workbook 'External workbook
Dim xWS As Worksheet 'External workbook
Dim RowNo As Long
Dim FN As String 'Data source filename
Dim FLDR As String 'Folder name
Dim FEXT As String 'Filename extension
Dim FPATH As String 'Full Path
Application.ScreenUpdating = False
'======================================================
' First, identify this workbook and its worksheets
'======================================================
Set WB = ActiveWorkbook
Set LST = WB.Sheets("DataSource")
'===============================================
' Get the:
' * data source folder name
' * data file name
' Make sure the folder name ends with a "\"
'===============================================
FLDR = LST.Range("C2")
FEXT = LST.Range("E2")
'=================================================
' Next, loop through the list of data sources
'=================================================
RowNo = 2
Do
'======================================================
' Get the data source filename
' Trim() = remove any leading- and trailing-spaces
'======================================================
FN = Trim(LST.Range("A" & RowNo))
'========================
' Form the full path
'========================
FPATH = FLDR & FN & FEXT
Application.StatusBar = "Copying data from: " & FPATH
'=================================
' Open the file, if it exist
'==================================
If Not Dir(FPATH) = "" Then
'============================
' Open the data workbook
'============================
Workbooks.Open FPATH
'================================
' Identify the data workbook
'================================
Set xWB = ActiveWorkbook
Set xWS = xWB.Sheets("Sheet1")
'=======================================================
' Clean up the destination worksheet before pasting
'=======================================================
WB.Sheets(FN).Cells.ClearContents
'===================
' Copy the data
'===================
xWS.Range("A1").CurrentRegion.Copy Destination:=WB.Sheets(FN).Range("A1")
'=============================
' Close the data workbook
'=============================
xWB.Close
End If
'======================
' Next data source
'======================
RowNo = RowNo + 1
Loop Until LST.Range("A" & RowNo) = ""
'========================
' Save this workbook
'========================
WB.Save
Application.StatusBar = "Data files have been copied."
Application.ScreenUpdating = True
End Sub