简体   繁体   中英

Excel VBA: How do I auto shift cells down when new data is inserted automatically?

To start off, I am new to using VB in excel. Here is my issue: I am using DreamReport to send out plant data to an excel file every 24 hours. I am using a single, static excel file.

The problem is that by using a static file, the data is replaced every day. This is because the data is automatically placed in the same group of cells, and the previous 24 hours get overwritten. Here is how the data is placed:

Excel表格

So, I need a script that will shift the new data, and all of the prior data down, immediately after the report adds the data from the screenshot, so that no data is overwritten.

Thanks in advance for anyone that helps! Please ask questions if I was not clear about anything.

As what I gather from what you have written and the screenshot the excel sheet gets fed the Rows 3 and 4 ( or maybe only row 3) by your other application-DreamReport. So with the given information you can paste the following code on the Sheet1(Sheet1) in the VBA editor of the Excel workbook. What happens now is everytime data is fed that data shifts down creating an empty range for next days data.

Press Alt+F11 to open VBA editor then double click the below sheet as in the picture. Once opened paste the below code. Then test and confirm. Double click this sheet to paste the code

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range

' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A3:C4")         ' Checks whether this range changed

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then

    Application.EnableEvents = False      ' disables events to avoid a loop
    Range("A3:C4").Insert Shift:=xlDown   ' shifts this range down
    Application.EnableEvents = True       ' ensures events are re-enabled

End If

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