Macro to create new sheets with certain data

CV12

Board Regular
Joined
Apr 6, 2020
Messages
82
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
Hello everyone,

Using an AI bot, I managed to get a VBA script that searches for a filter word, and copies the matching data in that row to a new sheet. The script seems to work, except that the target sheet is overwritten each time. In the image below, only a sheet named section3 has been created, since it is the last is the sequence. So the data in the red boxes, section 1 and section 2 are overwritten by section3. Does anyone see the error in the VBA script so that sheets are created for section1, 2 and 3?

Thanks!

1689794628225.png




VBA Code:
Sub FilterAndCopyRows()
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    Dim filterWords() As String
    Dim lastRow As Long
    Dim i As Long, j As Long, k As Long
    Dim copyRange As Range
    
    ' Set the source and target worksheets
    Set sourceSheet = ThisWorkbook.Sheets("BM1")
    
    ' Define filter words
    filterWords = Split("section1,section2,section3", ",")
    
    ' Filter and copy rows
    lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
    
    ' Iterate over filter words
    For k = LBound(filterWords) To UBound(filterWords)
        ' Check if the target sheet already exists, otherwise create it
        On Error Resume Next
        Set targetSheet = ThisWorkbook.Sheets(filterWords(k))
        On Error GoTo 0
        If targetSheet Is Nothing Then
            Set targetSheet = ThisWorkbook.Sheets.Add(After:=sourceSheet)
            targetSheet.Name = filterWords(k)
        End If
        
        j = 1
        Set copyRange = Nothing
        
        For i = 1 To lastRow
            If sourceSheet.Range("A" & i).Value = filterWords(k) Then
                If copyRange Is Nothing Then
                    Set copyRange = sourceSheet.Rows(i)
                Else
                    Set copyRange = Union(copyRange, sourceSheet.Rows(i))
                End If
            End If
        Next i
        
        ' Copy the range of matching rows to the target sheet
        If Not copyRange Is Nothing Then
            copyRange.Copy Destination:=targetSheet.Rows(j)
            j = j + copyRange.Rows.Count
        End If
        
        ' Options for the target sheet
        targetSheet.Columns.AutoFit
    Next k
    
    ' Select the source sheet
    sourceSheet.Select
End Sub
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
After this line:
VBA Code:
' Check if the target sheet already exists, otherwise create it

Put this line:
VBA Code:
Set targetSheet = Nothing


Full macro with ScreenUpdating instruction, just to make your macro faster.

Rich (BB code):
Sub FilterAndCopyRows()
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    Dim filterWords() As String
    Dim lastRow As Long
    Dim i As Long, j As Long, k As Long
    Dim copyRange As Range
   
    Application.ScreenUpdating = False
   
    ' Set the source and target worksheets
    Set sourceSheet = ThisWorkbook.Sheets("BM1")
   
    ' Define filter words
    filterWords = Split("section1,section2,section3", ",")
   
    ' Filter and copy rows
    lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
   
    ' Iterate over filter words
    For k = LBound(filterWords) To UBound(filterWords)
        ' Check if the target sheet already exists, otherwise create it
        Set targetSheet = Nothing
        On Error Resume Next
        Set targetSheet = ThisWorkbook.Sheets(filterWords(k))
        On Error GoTo 0
        If targetSheet Is Nothing Then
            Set targetSheet = ThisWorkbook.Sheets.Add(After:=sourceSheet)
            targetSheet.Name = filterWords(k)
        End If
       
        j = 1
        Set copyRange = Nothing
       
        For i = 1 To lastRow
            If sourceSheet.Range("A" & i).Value = filterWords(k) Then
                If copyRange Is Nothing Then
                    Set copyRange = sourceSheet.Rows(i)
                Else
                    Set copyRange = Union(copyRange, sourceSheet.Rows(i))
                End If
            End If
        Next i
       
        ' Copy the range of matching rows to the target sheet
        If Not copyRange Is Nothing Then
            copyRange.Copy Destination:=targetSheet.Rows(j)
            j = j + copyRange.Rows.Count
        End If
       
        ' Options for the target sheet
        targetSheet.Columns.AutoFit
    Next k
   
    ' Select the source sheet
    sourceSheet.Select
    Application.ScreenUpdating = True
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,224,822
Messages
6,181,165
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