Macro to open Workbook and paste data in empty sheet

howard

Well-known Member
Joined
Jun 26, 2006
Messages
6,589
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

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.

Forum statistics

Threads
1,223,099
Messages
6,170,107
Members
452,302
Latest member
TaMere

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