Esta resposta foi traduzida automaticamente. Como resultado, pode haver erros gramaticais ou palavras estranhas.
Olá Tiago Miranda1,
Obrigado por visitar a Comunidade da Microsoft.
Seus requisitos podem ser resumidos da seguinte forma:
- Quando novas linhas são adicionadas às Subtabelas 2, 3 e 4, os dados também devem ser registrados na Tabela Mestre 1.
- A modificação ou exclusão de dados nas subtabelas não deve afetar os dados na tabela mestre.
- Dados duplicados não devem ser adicionados.
Com base na captura de tela fornecida, parece que o conteúdo na Coluna D (Turno) e na Coluna F (ID) pode identificar exclusivamente um conjunto de dados. Portanto, podemos usar essas duas colunas para determinar se os dados são duplicados.
Aqui está o código VBA que escrevi para suas necessidades:
Sub MergeSheetsIntoSheet1()
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim lastRowSource As Long, lastRowTarget As Long
Dim i As Long, j As Long
Dim sheetNames() As Variant
' Set the target worksheet
Set wsTarget = ThisWorkbook.Sheets("Sheet1")
' Define the source sheet names
sheetNames = Array("Sheet2", "Sheet3", "Sheet4")
' Loop through each source sheet
For Each wsSourceName In sheetNames
Set wsSource = ThisWorkbook.Sheets(wsSourceName)
' Find the last row with data in the source sheet
lastRowSource = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row
' Find the last row with data in the target sheet
lastRowTarget = wsTarget.Cells(wsTarget.Rows.Count, "A").End(xlUp).Row
' Loop through each row in the source sheet
For i = 1 To lastRowSource
' Check if the current row is not in the target sheet
If Not IsRowInSheet(wsSource.Range("D" & i), wsSource.Range("F" & i), wsTarget) Then
' Insert a new row at the end of the target sheet
lastRowTarget = lastRowTarget + 1
wsTarget.Cells(lastRowTarget, 1).EntireRow.Insert Shift:=xlDown
' Copy the entire row from the source sheet to the target sheet
wsSource.Rows(i).Copy wsTarget.Rows(lastRowTarget)
End If
Next i
Next wsSourceName
End Sub
' Function to check if a row exists in a sheet based on D and F columns
Function IsRowInSheet(dColumnValue As Range, fColumnValue As Range, ws As Worksheet) As Boolean
Dim lastRow As Long
Dim cell As Range
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For Each cell In ws.Range("D1:D" & lastRow)
If cell.Value = dColumnValue.Value And ws.Range("F" & cell.Row).Value = fColumnValue.Value Then
IsRowInSheet = True
Exit Function
End If
Next cell
End Function
Você pode implementar isso no Excel navegando até o Developer > Visual Basic, inserindo um novo Module no lado esquerdo, colando o código lá e fechando a interface. Você pode executar a macro usando Alt+F8. Você precisará ajustar ligeiramente o código com base nos nomes específicos de suas tabelas. Se você tiver alguma dúvida, sinta-se à vontade para perguntar.
Atenciosamente
Jonathan Z - MSFT | Especialista em suporte da comunidade Microsoft