Forum Discussion
happyhourandtacos
Jul 19, 2024Copper Contributor
Copy rows from one set of sheets to another set of sheets, based on a condition
Hey all! Newbie, and could use some help, as I am not sure of the best way to achieve what I'm hoping to do 😀 Effectively, various focus areas for a company have been identified (IT, HR, FINANC...
happyhourandtacos
Jul 26, 2024Copper Contributor
Thank you for such a fulsome response!! I did try this out - I used ctrl a then ctrl v to copy and paste into the VBA editor and received and error message:
"Compile error:
For Each control variable must be Variant or Object"
"Compile error:
For Each control variable must be Variant or Object"
NikolinoDE
Jul 27, 2024Platinum Contributor
Sub CopyTasksToRegionSheets()
Dim focusAreas As Variant
Dim regions As Variant
Dim ws As Worksheet
Dim regionSheet As Worksheet
Dim lastRow As Long
Dim targetRow As Long
Dim region As String
Dim i As Long
Dim focusArea As Variant
' Define the focus area sheets and region sheets
focusAreas = Array("IT", "HR", "FINANCE", "COMMS", "SALES")
regions = Array("SOUTH", "NORTH", "WEST", "EAST", "CENTRAL")
' Clear the region sheets before copying new data
For Each region In regions
Set regionSheet = ThisWorkbook.Sheets(region)
' Assuming you want to clear all existing data except the header row
regionSheet.Rows("2:" & regionSheet.Rows.Count).ClearContents
Next region
' Loop through each focus area sheet
For Each focusArea In focusAreas
Set ws = ThisWorkbook.Sheets(focusArea)
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Loop through each row in the focus area sheet
For i = 2 To lastRow ' Assuming the first row is the header
region = ws.Cells(i, "B").Value ' Assuming region is in column B
' Copy the row to the corresponding region sheet
Set regionSheet = ThisWorkbook.Sheets(region)
targetRow = regionSheet.Cells(regionSheet.Rows.Count, "A").End(xlUp).Row + 1
ws.Rows(i).Copy Destination:=regionSheet.Rows(targetRow)
Next i
Next focusArea
MsgBox "Tasks have been successfully copied to their respective region sheets!"
End Sub
The error "For Each control variable must be Variant or Object" indicates that the control variable in your For Each loop must be declared as a Variant or Object. In the provided code, the control variable focusArea needs to be declared correctly.
In this code, I've declared focusArea as a Variant to avoid the compile error.
Hope this helps you.
- happyhourandtacosJul 31, 2024Copper Contributor
Hi there, thank you so much, but still receiving the same error. I did double check that I used the new code.
After I receive the error, when I go back to The VBA editor, if yiu look at line 17 (For Each region In regions), 'region' is highlighted.
When I ran the first code you gave me, it was the same error and same highlighted section.
- NikolinoDEAug 01, 2024Platinum ContributorYou need to adjust the file names in the code of your file.