Nas duas planilhas:
- Coluna A: Descrição dos produtos
- Coluna B: Quantidade dos produtos
Cole o código abaixo na classe da planilha Testes:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lLin As Long
Dim wsClientes As Worksheet
If Intersect(Target, Columns("A:B")) Is Nothing Then Exit Sub
Set wsClientes = ThisWorkbook.Sheets("Clientes")
lLin = flMatch(Cells(Target.Row, "A"), wsClientes.Columns("A"))
If lLin = 0 Then
If Cells(Target.Row, "B") <> 0 Then
lLin = flRowLast(wsClientes.Columns("A")) + 1
wsClientes.Cells(lLin, "A") = Cells(Target.Row, "A")
wsClientes.Cells(lLin, "B") = Cells(Target.Row, "B")
End If
Else
If Cells(Target.Row, "B") = 0 Then
wsClientes.Rows(lLin).Delete
Else
wsClientes.Cells(lLin, "B") = Cells(Target.Row, "B")
End If
End If
End Sub
Function flMatch(ByVal vTermo As Variant, ByVal vVetor As Variant) As Long
'Se vVetor for um objeto Range, retorna o número da linha ou coluna
'de uma célula com conteúdo vTermo numa linha ou coluna.
'Se vVetor for um vetor, retorna o índice do elemento vTermo no vetor.
'Caso não seja encontrada nenhuma ocorrência, é retornado 0.
Dim Temp 'As Long
On Error Resume Next
Temp = WorksheetFunction.Match(CStr(vTermo), vVetor, 0)
If Temp = 0 Then Temp = WorksheetFunction.Match(vTermo + 0, vVetor, 0)
On Error GoTo 0
If Temp > 0 Then
Select Case TypeName(vVetor)
Case "Range"
If vVetor.Columns.Count = 1 Then
'vVetor é uma coluna
Temp = Temp + vVetor.Row - 1
ElseIf vVetor.Rows.Count = 1 Then
'vVetor é uma linha
Temp = Temp + vVetor.Column - 1
End If
End Select
End If
flMatch = Temp
End Function
Function flRowLast(rng As Range) As Long
'Retorna o número da última linha povoada do intervalo rng
Dim Temp
With rng
On Error Resume Next
Temp = .Find(What:="*" _
, After:=.Cells(1) _
, SearchDirection:=xlPrevious _
, SearchOrder:=xlByColumns _
, LookIn:=xlFormulas).Row
If Temp = 0 Then Temp = rng.Cells(1).Row
End With
flRowLast = Temp
End Function
Felipe Costa Gualberto - http://www.ambienteoffice.com.br