I have an Excel sheet that connects to third party software which populates Sheet1 with data. It does this multiple times per second and overwrites previous data.
I have written the macro below to copy and paste the data to a sheet (called Data) each time there is a change to Sheet1.
The previous version of the macro looped down a range copying one row at a time which took a (relatively) long time as there can be 50000+ rows in the Data seet.
The current version uses a variant array but still seems to be very resource-hungry.
Are there any other ways it can be optimised to make it more efficient?
Thanks
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Columns.Count <> 16 Then Exit Sub
'Count the cells to copy
Dim a As Integer
With ThisWorkbook.Worksheets("Sheet1")
lastRow = .Cells(Rows.Count, "A").End(xlUp).Row
inarr = .Range(.Cells(1, 1), .Cells(lastRow + 5, 26)) ' load all of sheet 1 data in a variant array
End With
a = lastRow
'Count the last cell where to start copying
Dim b As Long
With ThisWorkbook.Worksheets("Data")
b = .Cells(Rows.Count, "A").End(xlUp).Row
Dim c As Integer
c = 5
'Perform the copy paste process
Dim outarr() As Variant
ReDim outarr(1 To a, 1 To 22)
Application.EnableEvents = False
For i = 1 To a - 1
If ThisWorkbook.Worksheets("Sheet1").Range("E2") <> "" And ThisWorkbook.Worksheets("Sheet1").Range("F2") = "" And ThisWorkbook.Worksheets("Sheet1").Range("AB5") = "35" Then
outarr(i, 1) = inarr(3, 14)
outarr(i, 2) = inarr(2, 2)
outarr(i, 3) = inarr(1, 1)
outarr(i, 4) = inarr(2, 5)
outarr(i, 5) = inarr(c, 26)
outarr(i, 6) = inarr(c, 1)
outarr(i, 7) = inarr(c, 6)
outarr(i, 8) = inarr(c, 8)
outarr(i, 9) = inarr(c, 15)
outarr(i, 10) = inarr(c, 16)
outarr(i, 11) = inarr(3, 2)
outarr(i, 12) = inarr(c, 7)
outarr(i, 13) = inarr(c, 2)
outarr(i, 14) = inarr(c, 3)
outarr(i, 15) = inarr(c, 4)
outarr(i, 16) = inarr(c, 5)
outarr(i, 17) = inarr(c, 9)
outarr(i, 18) = inarr(c, 12)
outarr(i, 19) = inarr(c, 13)
outarr(i, 20) = inarr(c, 10)
outarr(i, 21) = inarr(c, 11)
outarr(i, 22) = inarr(c, 25)
c = c + 1
End If
Next i
ThisWorkbook.Worksheets("Data").Range(.Cells(b + 1, 1), .Cells(b + a - 4, 22)) = outarr
End With
Application.EnableEvents = True
'End If
Dim lastcell As Range
Dim wsStore As Worksheet
Set wsStore = ThisWorkbook.Worksheets("Store")
Set lastcell = wsStore.Cells(wsStore.Rows.Count, 1).End(xlUp)
With ThisWorkbook.Worksheets("Sheet1").Range("F2")
're-set F2 when last cell of the Store sheet is no longer the same as the value in N3
If .Value = "Closed" And Val(.ID) <> xlOff Then
.ID = xlOff
Call CopyToStore
Call ClearData
ElseIf .Offset(1, 8).Value <> lastcell.Value Then
.ID = xlOn
End If
End With
End Sub
CopyToStore
andClearData
. Please add these functions. We can't tell where the bottleneck is without them. \$\endgroup\$