Private Sub ImportReport()
Dim i, endSourceRow As Integer
Dim temp, sourceRange, sourceFile As String
Application.DisplayAlerts = False
sourceFile = Application.GetOpenFilename("Excel files (*.xls; *.xlsx), *.xls; *.xlsx")
If InStr(sourceFile, "False") = 0 Then 'if user browses and selects a file to import
'-----------------------------------------------------------------
' 0 - Clear contents of the target tabs
'-----------------------------------------------------------------
ThisWorkbook.Worksheets("CFDS Report").Unprotect
ThisWorkbook.Worksheets("CFDS Report").Range("A:D").ClearContents
'-----------------------------------
' 1 - Open user selected source file
'-----------------------------------
Workbooks.Open Filename:=sourceFile, AddtoMRU:=True, Editable:=True
'Reset source file to contain just the name without path
sourceFile = Application.ActiveWorkbook.Name
'---------------------------------------------------
' 2 - Find out import data range from source file
'---------------------------------------------------
'Last line of data contains "Total:"
i = 5
Do While i > 0
temp = Workbooks(sourceFile).Sheets(1).Cells(i, 1).Value
If Trim(temp) = "Total:" Then
Exit Do
End If
i = i + 1
Loop
'Now endSourceRow contains the bottom range for copying
endSourceRow = i
sourceRange = "A1:D" & CStr(endSourceRow)
'-----------------------------------------------------------------
' 3 - Copy the source data range from source file
'-----------------------------------------------------------------
Workbooks(sourceFile).Sheets(1).Range(sourceRange).Select
Selection.Copy
'---------------------------------------------
' 4 - Paste the selection to the target file tab
'---------------------------------------------
ThisWorkbook.Worksheets("CFDS Report").Range(sourceRange).PasteSpecial Paste:=xlPasteAll
ThisWorkbook.Worksheets("CFDS Report").Protect
'----------------------------------------------------
' 5 - Close the source file and display Main tab
'----------------------------------------------------
Workbooks(sourceFile).Close SaveChanges:=False
ThisWorkbook.Worksheets("Main").Activate
Application.DisplayAlerts = True
Else
MsgBox "You didn't pick a file."
End Sub
Bookmarks