Sub MergeSheetsContainingAshan4() Dim SourceWorkbook As Workbook Dim SourceWorksheet As…
- User
Sub MergeSheetsContainingAshan4() Dim SourceWorkbook As Workbook Dim SourceWorksheet As Worksheet Dim TargetWorkbook As Workbook Dim TargetWorksheet As Worksheet Dim LastRow As Long Dim NextRow As Long Dim ExistingSheetRow As Long Dim SheetExists As Boolean Dim ContentMatch As Boolean Dim col As Long Dim TargetRow As Long
' ... ' (Previous code remains unchanged) ' ...
' If the sheet name and content do not match, copy the data If Not SheetExists Or Not ContentMatch Then ' Find the next empty row in column B on “Лист6” LastRow = TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 2).End(xlUp).Row + 1
' Copy the data from the found sheet to “Лист6” SourceWorksheet.UsedRange.Copy TargetWorksheet.Cells(LastRow, 2)
' Write the sheet name in column A on the same row where the data was copied NextRow = TargetWorksheet.Cells(TargetWorksheet.Rows.Count, 2).End(xlUp).Row + 1
With TargetWorksheet.Range("A" & LastRow & ":A" & NextRow - 1) .Value = SourceWorksheet.Name .HorizontalAlignment = xlCenter .VerticalAlignment = xlCenter End With
' Loop through each row in the copied data and remove rows with content not matching the source For TargetRow = LastRow To NextRow - 1 ContentMatch = True For col = 1 To SourceWorksheet.UsedRange.Columns.Count If SourceWorksheet.Cells(TargetRow - LastRow + 1, col).Value <> TargetWorksheet.Cells(TargetRow, col + 1).Value Then ContentMatch = False Exit For End If Next col
If Not ContentMatch Then TargetWorksheet.Rows(TargetRow).Delete TargetRow = TargetRow - 1 ' Adjust the target row after deleting NextRow = NextRow - 1 ' Adjust the next row after deleting End IfNext TargetRow End If
' ... ' (Next code remains unchanged) ' ...
End Sub
- Assistant
This updated code adds a loop that goes through each row in the copied data and compares the content with the corresponding data in the target worksheet. If the content does not match, the row is deleted.
Note that the code assumes that the source and target worksheets have the same number of columns, and that the data starts at row 1. If this is not the case, the code may need to be adjusted to match the actual layout of the data.