Advertisement
ayiemedia

27

Jul 27th, 2023
2,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sub TransferData()
  2.     Dim mainSheet As Worksheet
  3.     Dim destSheet As Worksheet
  4.     Dim lastRow As Long
  5.     Dim i As Long
  6.    
  7.     Set mainSheet = ThisWorkbook.Worksheets("Main")
  8.    
  9.     ' Loop through each district sheet and clear its data
  10.    For Each destSheet In ThisWorkbook.Worksheets
  11.         If destSheet.Name <> "Main" And destSheet.Name <> "Districts" Then
  12.             destSheet.Cells.ClearContents
  13.         End If
  14.     Next destSheet
  15.    
  16.     lastRow = mainSheet.Cells(mainSheet.Rows.Count, "A").End(xlUp).Row
  17.    
  18.     ' Loop through the rows in the main sheet and transfer data to the respective district sheets
  19.    For i = 2 To lastRow ' Assuming your data starts from row 2, change if necessary
  20.        Dim district As String
  21.         district = mainSheet.Cells(i, "E").Value ' Assuming the district column is column "E," change if necessary
  22.        
  23.         ' Find the respective district sheet and transfer the row data
  24.        On Error Resume Next
  25.         Set destSheet = ThisWorkbook.Worksheets(district)
  26.         On Error GoTo 0
  27.        
  28.         ' If the district sheet is found, transfer the row data
  29.        If Not destSheet Is Nothing Then
  30.             lastRow = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
  31.             destSheet.Rows(lastRow + 1).Value = mainSheet.Rows(i).Value
  32.         End If
  33.     Next i
  34. End Sub
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement