Loop through column, range.copy to another sheet based on cell value

vaemps

New Member
Joined
Apr 13, 2021
Messages
4
Office Version
  1. 2019
Platform
  1. Windows
I have code like this:

VBA Code:
Private Sub CommandButton2_Click()


    Dim i As Long
    Dim r As Long
    Dim Rng1 As Range
    Dim Rng2 As Range
    Dim Rng3 As Range
    
    With Sheets("sheet1")
    Set Rng1 = .Range("A2", .Range("A" & Rows.Count).End(xlUp))
    Set Rng2 = .Range("M2", .Range("M" & Rows.Count).End(xlUp))
    Set Rng3 = .Range("L2", .Range("L" & Rows.Count).End(xlUp))
    End With
    For i = 3 To Rng1.Count * 6 Step 6

If Rng3.Value = 1 Then
    Sheets("sheet2").Range("A1:B5").Copy _
    Destination:=Sheets("sheet3").Range("A" & i)
Elseif Rng3.Value = 2 Then
    Sheets("sheet2").Range("A5:B9").Copy _
    Destination:=Sheets("sheet3").Range("A" & i)
End If

      r = r + 1
    Sheets("sheet3").Range("A" & i).Value = Rng1(r).Value
    Sheets("sheet3").Range("B" & i).Value = Rng2(r).Value
      
    Next i
    
End Sub

Everything else I want is working properly, as it loops columns and inserts correct data to columns A and B. For the range.copy function I cannot get to work as I want it to. I want it to loop through column L and select correct range for copy based on that value. How I get this to work?
 

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)

Watch MrExcel Video

Forum statistics

Threads
1,133,271
Messages
5,657,765
Members
418,411
Latest member
Excellency

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top