I’ve been trying to optimize some of my coding and managed to cut and speed it up a lot. However there are some things that are still quite clunky (and me still a noob). Backstory is that my code is opening source and target files, copies a lot of data of variable length, closes source and then does a lot of operations and finally saves target file.
One of the things Id like is to do if possible is a direct copy of data without using clipboard, activating workbooks, selecting sheets (whatever of this is possible to pack into more efficient code that I am currently having)
Windows("SOURCE.xlsm").Activate Sheets("Data").Select Range("A2:AX10").Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Windows("TARGET.xlsm").Activate Range("A2").Select ActiveSheet.Paste Application.CutCopyMode = False
Is it possible to do a selection (A2:AX10 and all the way down to last row) in SOURCE file-Data sheet and directly copy it to TARGET file-Data sheet cell A2 without using clipboard.
The reason why I use A2:AX10 and then selection down is because I have a lot of blank cells in the whole data set and this way I get entire data.
I would like to be able to to that selection and use it as a range in this line
Workbooks(“SOURCE”).Worksheets("Data").Range(“A2:AX10 & ALLTHEWAYDOWN”).Copy _Workbooks(“TARGET”).Worksheets("Data").Range(“A2")
I was trying to solve this but I dont end up with desired result. When I try doing selection and setting as range then both trying copy range with activitng workbooks and in the direct copy mode I get 1004 error.
Is it possible to optimize this chunk and make it work. It would improve a lot of my VBA.
You need something like this:
With Workbooks("SOURCE.xlsm").Sheets("Data") .Range("A2:AX10", .Range("A2:AX10").End(xlDown)).Copy Workbooks("TARGET.xlsm").ActiveSheet.Range("A2") End With
You could probably also use
CurrentRegion rather than
You can set one range’s values (the range where you would want to paste values) equal to a source range’s values (the range which you would previously have copied).
Sub paste_values() Dim wb_A As Workbook, ws_A As Worksheet Dim wb_B As Workbook, ws_B As Worksheet Dim last_row As Long Set wb_A = ThisWorkbook Set ws_A = wb_A.Sheets(1) Set wb_B = Workbooks("WorkbookB") Set ws_B = wb_B.Sheets(1) With ws_A last_row = .Range("A" & .Rows.Count).End(xlUp).Row End With ws_B.Range("A2:AX" & last_row).Value = ws_A.Range("A2:AX" & last_row).Value End Sub
This code is setting the new range’s values equal to the original range. It prevents the need to activate sheets or workbooks, whilst also copying data to a range without filling the clipboard.
I would also recommend using
last_row = .Range("A" & .Rows.Count).End(xlUp).Row to find the last row of your data. Although you do need to ensure you use this on a column which you know contains continuous data.