简体   繁体   中英

How to automatically copy data entry from 1 workbook into another without having to activate macro or open workbook

I have come across a problem while trying to do the following:

I have 2 workbooks 1 called Master and the other one called Slave. Master has a worksheet called Data where data is inputted into it automatically every so often. Data is inputted into cells ranging from A8 to BL8. Every time new data is stored, it pushes the old data downwards and saves it into again A8:BL8. Slave has a worksheet called DATA with the exact same format.

My goal is the following:

I want to write a VBA code where each time new data is inputted into(USUALLY 6-7 NEW DATA ENTRIES PER 24 HOURS) Master workbook(Worksheet called Data), I want it to update the same information onto the Slave workbook (worksheet called DATA) without having to even open or run the workbook(Data can be inputted at random times throughout the day so I am not always around to keep track and need it to transfer data on its own).

Both workbooks are saved in different locations on my computer. My attempt worked, however I was only able to get it to work with copying the current values in the cell range A8:BL8 and moving it over to the workbook I want by triggering the macro with a button(inserting)... (I hope my problem is clear) so it only updates the very latest data and not ALL the data.

My goal eventually is to be able to do this between many workbooks with the same format (into the same workbook Slave(worksheet DATA))

My Code runs from workbook Slave (worksheet DATA) via a button assigned to this macro.

Sub OpenCopyPaste()

    Dim wb As Workbook
    Dim Reportwb As Workbook
    Set Reportwb = Workbooks("Slave.xlsm")
    Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu001          \Desktop\Master.xlsm")
    wb.Sheets("Data").Range("A8:BL8").Copy
    Reportwb.Sheets("DATA").Range("A8:BL8").Insert Shift:=xlDown
    Reportwb.Save
    wb.Close False
    Application.ScreenUpdating = True
End Sub

As per your comment, to run your code before save put the following into the ThisWorkbook object.

Private Sub Workbook_BeforeSave(Cancel As Boolean)

    Dim wb As Workbook
    Dim Reportwb As Workbook
    Set Reportwb = Workbooks("Slave.xlsm")
    Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu001          \Desktop\Master.xlsm")
    wb.Sheets("Data").Range("A8:BL8").Copy
    Reportwb.Sheets("DATA").Range("A8:BL8").Insert Shift:=xlDown
    Reportwb.Save
    wb.Close False
    Application.ScreenUpdating = True

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM