VOU MANDAR UMA MACRO E FAREI OS REQUERIMENTOS AO FINAL Sub…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
VOU MANDAR UMA MACRO E FAREI OS REQUERIMENTOS AO FINAL
Sub RegistrarPagamentosAdvocacia() ' ========== CONFIGURAÇÃO DO TIMER ========== Dim freq As Currency Dim startTime As Currency, endTime As Currency Dim tempoTotal As Double QueryPerformanceFrequency freq QueryPerformanceCounter startTime
' ========== CONFIGURAÇÕES INICIAIS OTIMIZADAS ==========
Dim oldScreenUpdating As Boolean
Dim oldCalculation As XlCalculation
Dim oldEvents As Boolean
oldScreenUpdating = Application.ScreenUpdating
oldCalculation = Application.Calculation
oldEvents = Application.EnableEvents
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
On Error GoTo ErroHandler
' ========== DECLARAÇÃO DE VARIÁVEIS ==========
Dim wsCusto As Worksheet, wsParcelas As Worksheet
Dim ultimaLinhaCusto As Long, ultimaLinhaParcelas As Long
Dim i As Long, j As Long, k As Long
Dim nomeCliente As String, nomeParcial As String
Dim tipoPagamento As String, tipoProcessamento As String
Dim numParcela As Integer, totalParcelas As Integer
Dim valorEsperado As Currency, valorPago As Currency
Dim dataPagamento As Date, resposta As String
Dim continuar As Boolean, processarTodos As Boolean
Dim clienteEncontrado As Boolean, clientePulado As Boolean
Dim clientesProcessados As Long, clientesPulados As Long
Dim parcelasProcessadas As Long
Dim parcelasIguais As String, tipoDiferenca As String
Dim dataPadrao As Date, valorPadrao As Currency
Dim linhaSelecionada As Long, confirmarNome As String
' ========== INICIALIZAÇÃO DAS PLANILHAS ==========
Set wsCusto = ThisWorkbook.Sheets("PLANILHA DE CUSTO DA ADVOCACIA")
Set wsParcelas = ThisWorkbook.Sheets("VER N° PARCELAS E PAGAMENTOS")
ultimaLinhaCusto = wsCusto.Cells(wsCusto.Rows.Count, "A").End(xlUp).row
ultimaLinhaParcelas = wsParcelas.Cells(wsParcelas.Rows.Count, "A").End(xlUp).row
' ========== SELEÇÃO DO TIPO DE PROCESSAMENTO ==========
tipoProcessamento = UCase(InputBox("Deseja processar:" & vbCrLf & _
"1 - Um cliente específico" & vbCrLf & _
"2 - Todos os clientes" & vbCrLf & _
"Digite 1 ou 2:", "Tipo de Processamento", "1"))
If tipoProcessamento = "" Then GoTo FinalizarMacro
If tipoProcessamento <> "1" And tipoProcessamento <> "2" Then
MsgBox "Opção inválida! Processamento cancelado.", vbExclamation
GoTo FinalizarMacro
End If
processarTodos = (tipoProcessamento = "2")
' ========== PROCESSAMENTO PRINCIPAL ==========
clientesProcessados = 0
clientesPulados = 0
parcelasProcessadas = 0
continuar = True
Do ' Loop principal para permitir processar múltiplos clientes específicos
If processarTodos Then
' Processar todos os clientes automaticamente
For i = 15 To ultimaLinhaCusto
nomeCliente = wsCusto.Cells(i, 1).Value
If nomeCliente = "" Then Exit For
ProcessarCliente wsCusto, wsParcelas, i, clientesProcessados, clientesPulados, parcelasProcessadas, processarTodos
' Atualizar status bar
Application.StatusBar = "Processando... " & clientesProcessados & " clientes registrados, " & _
clientesPulados & " pulados, " & parcelasProcessadas & " parcelas processadas"
Next i
Exit Do ' Sair do loop após processar todos
Else
' Processar cliente específico
Do
resposta = InputBox("Como deseja selecionar o cliente?" & vbCrLf & _
"1 - Digitar o nome" & vbCrLf & _
"2 - Informar o número da linha" & vbCrLf & _
"Digite 1 ou 2:", "Seleção de Cliente", "1")
If StrPtr(resposta) = 0 Then ' Usuário clicou em Cancelar
continuar = False
Exit Do
End If
If resposta = "1" Then
' Seleção por nome
nomeParcial = InputBox("Digite parte do nome do cliente:", "Seleção por Nome")
If nomeParcial = "" Then
If MsgBox("Deseja cancelar o processamento?", vbQuestion + vbYesNo) = vbYes Then
continuar = False
Exit Do
End If
Else
' Procurar cliente pelo nome
clienteEncontrado = False
For i = 15 To ultimaLinhaCusto
If InStr(1, wsCusto.Cells(i, 1).Value, nomeParcial, vbTextCompare) > 0 Then
nomeCliente = wsCusto.Cells(i, 1).Value
linhaSelecionada = i
clienteEncontrado = True
Exit For
End If
Next i
If Not clienteEncontrado Then
MsgBox "Cliente não encontrado!", vbExclamation
Else
Exit Do
End If
End If
ElseIf resposta = "2" Then
' Seleção por linha com confirmação do nome
Do
resposta = InputBox("Digite o número da linha do cliente (15 a " & ultimaLinhaCusto & "):", "Seleção por Linha")
If StrPtr(resposta) = 0 Then ' Usuário clicou em Cancelar
continuar = False
Exit Do
End If
If IsNumeric(resposta) Then
linhaSelecionada = CLng(resposta)
If linhaSelecionada >= 15 And linhaSelecionada <= ultimaLinhaCusto Then
nomeCliente = wsCusto.Cells(linhaSelecionada, 1).Value
If nomeCliente <> "" Then
' Confirmar nome do cliente
confirmarNome = InputBox("O cliente na linha " & linhaSelecionada & " é: " & nomeCliente & vbCrLf & _
"Confirma? (S/N)", "Confirmação", "S")
If UCase(confirmarNome) = "S" Then
i = linhaSelecionada
Exit Do
ElseIf UCase(confirmarNome) = "N" Then
MsgBox "Por favor, selecione novamente.", vbInformation
Else
continuar = False
Exit Do
End If
Else
MsgBox "Linha vazia! Selecione outra linha.", vbExclamation
End If
Else
MsgBox "Número de linha inválido! Deve ser entre 15 e " & ultimaLinhaCusto, vbExclamation
End If
Else
MsgBox "Digite um número válido!", vbExclamation
End If
Loop
If Not continuar Then Exit Do
Else
MsgBox "Opção inválida! Digite 1 ou 2.", vbExclamation
End If
Loop
If Not continuar Then Exit Do
' Processar o cliente selecionado
ProcessarCliente wsCusto, wsParcelas, i, clientesProcessados, clientesPulados, parcelasProcessadas, processarTodos
' Perguntar se deseja processar outro cliente
resposta = MsgBox("Cliente processado com sucesso!" & vbCrLf & _
"Deseja processar outro cliente?", vbQuestion + vbYesNo)
If resposta = vbNo Then Exit Do
End If
Loop
' ========== ATUALIZAR STATUS DOS PAGAMENTOS ==========
Application.StatusBar = "Atualizando status de pagamentos..."
Application.Run "AtualizarStatusPagamentosAdvocacia"
' ========== FINALIZAÇÃO ==========
QueryPerformanceCounter endTime
tempoTotal = (endTime - startTime) / freq * 1000 'ms
FinalizarMacro: ' Restaurar configurações do Excel Application.ScreenUpdating = oldScreenUpdating Application.Calculation = oldCalculation Application.EnableEvents = oldEvents Application.StatusBar = False
' Relatório de performance
MsgBox "PROCESSAMENTO CONCLUÍDO!" & vbCrLf & vbCrLf & _
"Tempo total: " & Format(tempoTotal / 1000, "0.000") & " segundos" & vbCrLf & _
"Clientes processados: " & clientesProcessados & vbCrLf & _
"Clientes pulados: " & clientesPulados & vbCrLf & _
"Parcelas registradas: " & parcelasProcessadas & vbCrLf & _
"Atualizado em: " & Format(Now, "dd/mm/yyyy HH:mm:ss"), _
vbInformation, "Relatório de Execução"
Exit Sub
ErroHandler: QueryPerformanceCounter endTime tempoTotal = (endTime - startTime) / freq * 1000 'ms
Application.ScreenUpdating = oldScreenUpdating
Application.Calculation = oldCalculation
Application.EnableEvents = oldEvents
Application.StatusBar = False
MsgBox "ERRO NO PROCESSAMENTO: " & Err.Description & vbCrLf & _
"Tempo decorrido: " & Format(tempoTotal / 1000, "0.000") & " segundos" & vbCrLf & _
"Clientes processados até o erro: " & clientesProcessados, vbCritical
End Sub
QUERO QUE QUANDO FAÇA O REGISTRO DO PAGAMENTO, QUE COLOQUE, PARA ALÉM DE COMO ESTAR, O VALOR DEVIDO/VALOR PAGO, CASO O PAGAMENTO SEJA PARCIAL, POR EXEMPLO, SE O CLIENTE DEVE 7500 E PAGOU APENAS 5000, PARA UMA DETERMINADA PARCELA, DEVE FICAR 7500/5000, PARA AQUELA PARCELA, OUTRA COISA, É QUE CASO O CLIENTE PAGUE A MAIS, QUE FIQUE O TETO DO DEVIDO PARA A PARCELA MAIS ANTIGA E O RESTANTE VA PARA A PROIMA, OU PROXIMAS, EXEMPLO, CASO O CLINTE DEVA 5 PARCELAS, CADA UMA DE 10000 REAIS, CASO EU CADASTRE QUE ELE PAGOU 45000 REAIS, AS 4 PRIMEIRAS PARCELAS DEVE FICAR 10000/10000 (MOSTRANDO QUE FOI PAGO NA INTEGRA) E A ULTIMA DEVE APARECER 10000/5000 (MOSTRANDO QUE O CLIENTE DEVE, AINDA, 5000 REAIS) E, POR FIM, QUERO QUE EXECUTE, CASO AINDA NÃO CHAME, A MACRO AtualizarStatusPagamentosAdvocacia AO FINAL
Vou propor as alterações necessárias para atender aos seus requisitos:
Formatação de valores devidos/pagos:
Distribuição de pagamentos em excesso:
Chamada automática da macro de atualização:
AtualizarStatusPagamentosAdvocacia seja chamada ao finalSub RegistrarPagamentosAdvocacia()
' ========== CONFIGURAÇÃO DO TIMER ==========
Dim freq As Currency
Dim startTime As Currency, endTime As Currency
Dim tempoTotal As Double
QueryPerformanceFrequency freq
QueryPerformanceCounter startTime
' ========== CONFIGURAÇÕES INICIAIS OTIMIZADAS ==========
Dim oldScreenUpdating As Boolean
Dim oldCalculation As XlCalculation
Dim oldEvents As Boolean
oldScreenUpdating = Application.ScreenUpdating
oldCalculation = Application.Calculation
oldEvents = Application.EnableEvents
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
On Error GoTo ErroHandler
' ========== DECLARAÇÃO DE VARIÁVEIS ==========
Dim wsCusto As Worksheet, wsParcelas As Worksheet
Dim ultimaLinhaCusto As Long, ultimaLinhaParcelas As Long
Dim i As Long, j As Long, k As Long
Dim nomeCliente As String, nomeParcial As String
Dim tipoPagamento As String, tipoProcessamento As String
Dim numParcela As Integer, totalParcelas As Integer
Dim valorEsperado As Currency, valorPago As Currency, valorRestante As Currency
Dim dataPagamento As Date, resposta As String
Dim continuar As Boolean, processarTodos As Boolean
Dim clienteEncontrado As Boolean, clientePulado As Boolean
Dim clientesProcessados As Long, clientesPulados As Long
Dim parcelasProcessadas As Long
Dim parcelasIguais As String, tipoDiferenca As String
Dim dataPadrao As Date, valorPadrao As Currency
Dim linhaSelecionada As Long, confirmarNome As String
' ========== INICIALIZAÇÃO DAS PLANILHAS ==========
Set wsCusto = ThisWorkbook.Sheets("PLANILHA DE CUSTO DA ADVOCACIA")
Set wsParcelas = ThisWorkbook.Sheets("VER N° PARCELAS E PAGAMENTOS")
ultimaLinhaCusto = wsCusto.Cells(wsCusto.Rows.Count, "A").End(xlUp).row
ultimaLinhaParcelas = wsParcelas.Cells(wsParcelas.Rows.Count, "A").End(xlUp).row
' ========== SELEÇÃO DO TIPO DE PROCESSAMENTO ==========
tipoProcessamento = UCase(InputBox("Deseja processar:" & vbCrLf & _
"1 - Um cliente específico" & vbCrLf & _
"2 - Todos os clientes" & vbCrLf & _
"Digite 1 ou 2:", "Tipo de Processamento", "1"))
If tipoProcessamento = "" Then GoTo FinalizarMacro
If tipoProcessamento <> "1" And tipoProcessamento <> "2" Then
MsgBox "Opção inválida! Processamento cancelado.", vbExclamation
GoTo FinalizarMacro
End If
processarTodos = (tipoProcessamento = "2")
' ========== PROCESSAMENTO PRINCIPAL ==========
clientesProcessados = 0
clientesPulados = 0
parcelasProcessadas = 0
continuar = True
Do ' Loop principal para permitir processar múltiplos clientes específicos
If processarTodos Then
' Processar todos os clientes automaticamente
For i = 15 To ultimaLinhaCusto
nomeCliente = wsCusto.Cells(i, 1).Value
If nomeCliente = "" Then Exit For
ProcessarCliente wsCusto, wsParcelas, i, clientesProcessados, clientesPulados, parcelasProcessadas, processarTodos
' Atualizar status bar
Application.StatusBar = "Processando... " & clientesProcessados & " clientes registrados, " & _
clientesPulados & " pulados, " & parcelasProcessadas & " parcelas processadas"
Next i
Exit Do ' Sair do loop após processar todos
Else
' Processar cliente específico
Do
resposta = InputBox("Como deseja selecionar o cliente?" & vbCrLf & _
"1 - Digitar o nome" & vbCrLf & _
"2 - Informar o número da linha" & vbCrLf & _
"Digite 1 ou 2:", "Seleção de Cliente", "1")
If StrPtr(resposta) = 0 Then ' Usuário clicou em Cancelar
continuar = False
Exit Do
End If
If resposta = "1" Then
' Seleção por nome
nomeParcial = InputBox("Digite parte do nome do cliente:", "Seleção por Nome")
If nomeParcial = "" Then
If MsgBox "Deseja cancelar o processamento?", vbQuestion + vbYesNo = vbYes Then
continuar = False
Exit Do
End If
Else
' Procurar cliente pelo nome
clienteEncontrado = False
For i = 15 To ultimaLinhaCusto
If InStr(1, wsCusto.Cells(i, 1).Value, nomeParcial, vbTextCompare) > 0 Then
nomeCliente = wsCusto.Cells(i, 1).Value
linhaSelecionada = i
clienteEncontrado = True
Exit For
End If
Next i
If Not clienteEncontrado Then
MsgBox "Cliente não encontrado!", vbExclamation
Else
Exit Do
End If
End If
ElseIf resposta = "2" Then
' Seleção por linha com confirmação do nome
Do
resposta = InputBox("Digite o número da linha do cliente (15 a " & ultimaLinhaCusto & "):", "Seleção por Linha")
If StrPtr(resposta) = 0 Then ' Usuário clicou em Cancelar
continuar = False
Exit Do
End If
If IsNumeric(resposta) Then
linhaSelecionada = CLng(resposta)
If linhaSelecionada >= 15 And linhaSelecionada <= ultimaLinhaCusto Then
nomeCliente = wsCusto.Cells(linhaSelecionada, 1).Value
If nomeCliente <> "" Then
' Confirmar nome do cliente
confirmarNome = InputBox("O cliente na linha " & linhaSelecionada & " é: " & nomeCliente & vbCrLf & _
"Confirma? (S/N)", "Confirmação", "S")
If UCase(confirmarNome) = "S" Then
i = linhaSelecionada
Exit Do
ElseIf UCase(confirmarNome) = "N" Then
MsgBox "Por favor, selecione novamente.", vbInformation
Else
continuar = False
Exit Do
End If
Else
MsgBox "Linha vazia! Selecione outra linha.", vbExclamation
End If
Else
MsgBox "Número de linha inválido! Deve ser entre 15 e " & ultimaLinhaCusto, vbExclamation
End If
Else
MsgBox "Digite um número válido!", vbExclamation
End If
Loop
If Not continuar Then Exit Do
Else
MsgBox "Opção inválida! Digite 1 ou 2.", vbExclamation
End If
Loop
If Not continuar Then Exit Do
' Processar o cliente selecionado
ProcessarCliente wsCusto, wsParcelas, i, clientesProcessados, clientesPulados, parcelasProcessadas, processarTodos