Macro to open Workbook and paste data in empty sheet

howard

Well-known Member
Joined
Jun 26, 2006
Messages
6,570
Office Version
  1. 2021
Platform
  1. Windows
I have the following macro below when allows me to select the source file and to copy the data into sheet1 of the destination sheet

I would like the macro amended so that if sheet1 has data in it, then the data must be pasted into the next blank sheet (if no sheet then to insert a sheet)


Code:
 Sub copyDataFromSource()
Dim sourceBook As Workbook
Dim destinationBook As Workbook
Dim sourceSheet As Worksheet
Dim destinationSheet As Worksheet
Dim fileSource, sourceRow%, sourceRowCount&, destRow%
With Application
    .ScreenUpdating = False
End With
fileSource = Application.GetOpenFilename
If fileSource = False Or IsEmpty(fileSource) Then Exit Sub
Set destinationBook = ThisWorkbook
Set destinationSheet = destinationBook.Sheets("sheet1")
Set sourceBook = Workbooks.Open(fileSource)
Set sourceSheet = sourceBook.Sheets(1)
sourceRow = sourceSheet.Cells(sourceSheet.Rows.Count, 1).End(xlUp).Row
sourceRowCount = sourceRow - 1
destRow = destinationSheet.Cells(destinationSheet.Rows.Count, 1).End(xlUp).Row
destinationSheet.Rows(destRow + 1).Resize(sourceRowCount).Insert
destRow = destRow

With destinationSheet
    .Range("a" & destRow & ":z" & destRow + sourceRowCount - 1).Value = sourceSheet.Range("a1:z" & sourceRow).Value
   
End With
sourceBook.Close False
With Application
    .ScreenUpdating = True
End With
Set sourceBook = Nothing
Set destinationBook = Nothing
Set sourceSheet = Nothing
Set destinationSheet = Nothing
End Sub
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).

Forum statistics

Threads
1,215,978
Messages
6,128,063
Members
449,416
Latest member
SHIVANISHARMA1711

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top