troubleshooting Question

VBA: How to copy every nth row into multiple new worksheets?

Avatar of Ryan Simmons
Ryan Simmons asked on
Microsoft OfficeMicrosoft ExcelVisual Basic Classic
5 Comments1 Solution268 ViewsLast Modified:
I am trying to loop through a spreadsheet and copy every 5th row of a sheet into multiple new worksheets. Basically every 5 rows of data should be placed into a new worksheet. The code I am trying to modify to suit my purposes is

Option Explicit

Sub loopTest()
Dim hdr As Range 'header range
Dim dta As Range 'data range
Dim cl As Integer 'copy line
Dim ns As Excel.Worksheet

Set hdr = Excel.Worksheets(1).Range("A2:Q2") 'set this range for what ever range your headers are on
cl = 3 'set this value for what ever row your data starts on
Do While Excel.Worksheets(1).Range(Cells(cl, 1), Cells(cl, 1)).Value <> "" 'this stops the loop when there are no more records
Set dta = Excel.Worksheets(1).Range(Cells(cl, 1), Cells(cl + 2, 17)) 'this sets the data range change the number 3 to how ever many columns there are in your dataset
Set ns = Excel.Worksheets.Add(, ActiveSheet) 'this sets the new sheet to the ns (new sheet = ns ) variable
hdr.Copy
ns.Range("A1").PasteSpecial xlPasteAll
dta.Copy
ns.Range("A2").PasteSpecial xlPasteAll
cl = cl + 5
Loop

End Sub

I currently get an error on the line:
Do While Excel.Worksheets(1).Range(Cells(cl, 1), Cells(cl, 1)).Value <> "" 'this stops the loop when there are no more records

The error I am receiving is Application-defined or object-defined error. I am unsure how to interpret this error.

testworkbook with the code and error is attached.
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 5 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros