Reputation: 15
Hi I'm fairly new to VBA and I want to loop this code. as of right now this code is copying data in Range ("B30:B") from the "Ba Pricing" to the destination worksheet and it will copy the same data to the last cell. What I wanted this to do is loop this code where it will copy the data in columns (E, H, K and N) and paste it to last cell of the "Loader" worksheet. with the condition if there is no data in each column then don't copy.
Thanks
Sub Copy_Paste_Below_Last_Cell()
'Find the last used row in both sheets and copy and paste data below existing data.
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long
'Set variables for copy and destination sheets
Set wsCopy = ThisWorkbook.Worksheets("Ba pricing")
Set wsDest = ThisWorkbook.Worksheets("Loader")
'1. Find last used row in the copy range based on data in column A
lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "B").End(xlUp).Row
'2. Find first blank row in the destination range based on data in column A
'Offset property moves down 1 row
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "C").End(xlUp).Offset(1).Row
'3. Copy & Paste Data
wsCopy.Range("B30:B" & lCopyLastRow).Copy
wsDest.Range("C" & lDestLastRow).PasteSpecial xlPasteValues
End Sub
It should look something like this...
PriceDate
4/23/2019
4/24/2019
4/25/2019
4/26/2019
4/27/2019
4/28/2019
4/29/2019
4/30/2019
5/1/2019
5/2/2019
5/3/2019
5/4/2019
5/5/2019
5/6/2019
5/7/2019
5/8/2019
5/9/2019
5/10/2019
5/11/2019
5/12/2019
5/13/2019
5/14/2019
5/15/2019
5/16/2019
4/23/2019
4/24/2019
4/25/2019
4/26/2019
4/27/2019
4/28/2019
4/29/2019
4/30/2019
5/1/2019
5/2/2019
5/3/2019
5/4/2019
5/5/2019
5/6/2019
4/23/2019
Upvotes: 0
Views: 788
Reputation: 57683
Here is an example how to loop through columns
Dim CopyColumns() As Variant
CopyColumns = Array("B", "E", "H", "K", "N")
Dim Col As Variant
For Each Col In CopyColumns
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "C").End(xlUp).Offset(1).Row
lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, Col).End(xlUp).Row
wsCopy.Range(Col & "30:" & Col & lCopyLastRow).Copy
wsDest.Range("C" & lDestLastRow).PasteSpecial xlPasteValues
Next Col
Upvotes: 1