Loop to copy row but get duplicated when condition match

tendosai

New Member
Joined
Mar 14, 2022
Messages
26
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
I want to copy from MasterList sheet to new sheet (which will name after the value in column L). I looped and it worked ok if value in "L" is different. However, the problem occur when the value in "L" is the same. This will lead to each copy loop thru the range and duplicate the copy row in other sheet.
this is the sample Sample for testing.xlsm which i also include the code i did.

extra question:
with above copy, i plan to make it automatically run with using the button. so when my user enter new data and it will create new sheet (with the name from "L") and copy that row to it. OR if sheet exist it will just copy the row. HOWEVER, if the row exist (base on ID value) it will just update the existing data in the sheet.
 

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
for extra question: i want sheet update automatically without using button
 
Upvote 0
Maybe helps you...

VBA Code:
Sub AddSheetsMonth()
    
    Const ProcTitle As String = "Add Sheets Month"
    
    Const swsName As String = "Sheet1" 'Name Sheet
    Const sCol As Long = 12
    Const dFirstCellAddress As String = "A1"
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    
    Dim sws As Worksheet: Set sws = wb.Worksheets(swsName)
    If sws.AutoFilterMode Then sws.AutoFilterMode = False
    
    Dim srg As Range: Set srg = sws.Range("A1").CurrentRegion ' Source Range
    Dim srCount As Long: srCount = srg.Rows.Count ' Source Rows Count
    
    If srCount < 2 Then Exit Sub ' just headers or no data at all
    Dim sData As Variant: sData = srg.Columns(sCol).Value
    
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    
    Dim dKey As Variant
    Dim dString As String
    Dim r As Long
    
    ' Write the unique strings to a dictionary.
    For r = 2 To srCount
        dKey = sData(r, 1)
        If Not IsError(dKey) Then
            If Len(dKey) > 0 Then
                dString = CStr(dKey)
                If StrComp(dString, swsName, vbTextCompare) <> 0 Then
                    dict(dString) = Empty
                End If
            End If
        End If
    Next r
    If dict.Count = 0 Then Exit Sub ' only blanks and error values and whatnot
    Erase sData
     
    Application.ScreenUpdating = False
    
    Dim scrg As Range ' Source Copy Range
    
    Dim dws As Object
    Dim dwsName As String
    
    For Each dKey In dict.Keys
        ' Restrict to maximum allowed characters (31).
        dwsName = dKey
        If Len(dwsName) > 9 Then
            dwsName = Left(dwsName, 9)
            Debug.Print "'" & dKey & "' is too long." & vbLf _
                & "'" & dwsName & "' is used in the continuation." ' log
        End If
        ' Delete possibly existing sheet.
        On Error Resume Next
            Set dws = wb.Sheets(dwsName)
        On Error GoTo 0
        If Not dws Is Nothing Then ' destination sheet exists
            Application.DisplayAlerts = False
            dws.Delete
            Application.DisplayAlerts = True
        'Else ' destination sheet doesn't exist
        End If
        ' Create a reference to a newly added (destination) worksheet.
        Set dws = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))
        ' Rename Destination Worksheet.
        On Error Resume Next
            dws.Name = dwsName
            If Err.Number <> 0 Then ' invalid sheet name
                ' log
                Debug.Print "'" & dwsName & "' cannot be used as a sheet name."
            'Else ' valid sheet name
            End If
        On Error GoTo 0
        ' Create a reference to the Source Copy Range.
        srg.AutoFilter sCol, dKey
        Set scrg = srg.SpecialCells(xlCellTypeVisible) ' headers are visible
        sws.AutoFilterMode = False
        ' Copy the Source Copy Range to the Destination Worksheet.
        scrg.Copy dws.Range(dFirstCellAddress)
        
            With dws
                .UsedRange.EntireColumn.AutoFit
            End With
        ' Initialize Destination Worksheet variable (reference).
        Set dws = Nothing
    Next dKey
        
    sws.Activate
        
    Application.ScreenUpdating = True
    
    MsgBox "Done", vbInformation, ProcTitle

End Sub

I think that add to button gets better
 
Upvote 0
Solution
wow thank so much. so many new things to learn.
example: in "L" the value change from January to April which does not match the existing sheet "January" anymore ... therefore there should not be any data in the "January" or might as well delete the sheet.
 
Upvote 0
wow thank so much. so many new things to learn.
example: in "L" the value change from January to April which does not match the existing sheet "January" anymore ... therefore there should not be any data in the "January" or might as well delete the sheet.
For each month described in column L , this macro will add sheet
 
Upvote 0
yes but left the sheet of month that no longer exist in L .. i loop thru sheet.name to remove it
 
Upvote 0

Forum statistics

Threads
1,215,219
Messages
6,123,692
Members
449,117
Latest member
Aaagu

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