excelvba

Copying between two different workbooks with VBA


I got a code to copy data from a closed workbook to another active workbook but I have a probelm in closing workbooks after runing the code I don't know how to fix it

my source Workbook is "Stop Work" sheet1 and the destination workbook is "AUTHS" and sheet name is "stop work" the code run smoothly but my probelm is that after runnig the code and copying the data my active workbook which I'm working on it "AUTHS" get closed and the source workbook which was closed get opened while i need the vice versa (to save and close "stop Work" and keep "AUTHS" open - I Have tried changing true and false but nothing done this is my code

Sub mycode()

Workbooks.Open Filename:="D:\Desktop\Stop Work.xlsm"
Worksheets("Sheet1").Cells.Select
Selection.Copy

Workbooks.Open Filename:="D:\Desktop\AUTHs.xlsm"
Worksheets("Stop Work").Cells.Select
Selection.PasteSpecial xlPasteAll             'xlPasteAll to paste everything
ActiveWorkbook.Save

ThisWorkbook.Close SaveChanges:=False        'to close the file
Workbooks("D:\Desktop\Stop Work.xlsm").Close SaveChanges:=True  'to close the file

End Sub



thank you in advance        

Solution

  • Better to use variables to identify the workbooks. Something like below

    ' Open the source workbook  
    Set sourceWorkbook = Workbooks.Open(Filename:="D:\Desktop\Stop Work.xlsm")  
    
    sourceWorkbook.Worksheets("Sheet1").Cells.Copy  
    
    ' Open the destination workbook  
    Set destinationWorkbook = Workbooks.Open(Filename:="D:\Desktop\AUTHs.xlsm")  
     
    destinationWorkbook.Worksheets("Stop Work").Cells.PasteSpecial xlPasteAll  
    
    destinationWorkbook.Save  
    
    ' Close the source workbook after saving changes  
    sourceWorkbook.Close SaveChanges:=False