Button for a For Loop

Gryder

New Member
Joined
Aug 26, 2020
Messages
21
Office Version
  1. 2016
Platform
  1. Windows
Hello,

I have some code that works but not exactly how I want it to work. When I press my transfer button, it sends the data to the other two sheets (Week, Month) but only one row at time, sometimes more than one row. I have to keep pressing the button until all data is moved over.

I want my code to send all data from the rows to the other sheets with once press. I believe I need a loop but have searched and tried different code with no success. Code is below. Any help is appreciated. Garrett


Private Sub CommandButton1_Click()

Application.ScreenUpdating = False

Dim i As Long
Dim Lastrow As Long

Lastrow = Cells(Rows.Count, "A").End(xlUp).Row

For i = 4 To Lastrow

If Cells(i, 7) = "Not Due" And Cells(i, 9) = "Week" Then
Rows(i).Copy Destination:=Sheets("Week").Range("A1048576").End(xlUp).Offset(1, 0)
Rows(i).Delete

ElseIf Cells(i, 7) = "Not Due" And Cells(i, 9) = "Month" Then
Rows(i).Copy Destination:=Sheets("Month").Range("A1048576").End(xlUp).Offset(1, 0)
Rows(i).Delete

End If
Next i
Application.ScreenUpdating = True

End Sub
 

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
When deleting or inserting rows, it is best to work backwards through your range, as you may be moving data into a range you already checked (when deleting).

So, change your loop line to this:
VBA Code:
For i = Lastrow to 4 Step -1
 
Upvote 1
Solution
You are welcome.
Glad I was able to help!

Just remember, whenever inserting or deleting rows, it is always best to loop through your rows backwards.
 
Upvote 0

Forum statistics

Threads
1,224,812
Messages
6,181,105
Members
453,021
Latest member
Justyna P

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
Back
Top