Ajuda sobre ModeloCadastro_v2 Adaptado

mauribeiro82

07-10-2014 14:25:13

Primeiramente parabéns e obrigado pelo modelo de cadastro que você disponibilizou já alguns anos no seu site, pois me ajudou muito.
A partir do seu ModeloCadastro_v2 eu adaptei outro aplicativo. Contudo na form de Pesquisa a adaptação que eu fiz, gerou alguma inconsistência que não está funcionando.

Poderia me ajuda? Enviei a planilha para seu email.

Login: usuario
Senha:123

'Cadastro de movimentação de pallet em VBA no MS-Excel: 'FORMULÁRIO DE CADASTRO'

Option Explicit

Const colCodigoDoRegistro As Integer = 1
Const colDataDoRegistro As Integer = 2
Const colNomeDaOperacao As Integer = 3
Const colDeIdentificacao As Integer = 4
Const colNTransporte As Integer = 5
Const colDeQuantidade As Integer = 6
Const colDeValePallet As Integer = 7
Const colDeConferencia As Integer = 8
Const colDePlaca As Integer = 9
Const colDeMotorista As Integer = 10
Const colDeObs As Integer = 11
Const indiceMinimo As Byte = 2
Const corDisabledTextBox As Long = -2147483633
Const corEnabledTextBox As Long = -2147483643

Private wsCadastro As Worksheet
Private indiceRegistro As Long
Private Sub cboNomeOperacao_Change()
If cboNomeOperacao.Value = "(-)Envio de pallet - cliente" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!B2:B68"
lblMensagem.Caption = "Opção usada para registrar envio de pallet com produto para cliente que faz retenção de pallet"
ElseIf cboNomeOperacao.Value = "(+)Recebimento de pallet - cliente" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!B2:B68"
lblMensagem.Caption = "Opção usada para registrar o recebimento/devolução de pallet do cliente"
ElseIf cboNomeOperacao.Value = "(-)Envio de pallet - transportadora" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!C2:C6"
lblMensagem.Caption = "Opção usada para registrar o 'emprestimo' de pallet a transportadora no ato da coleta de produto"
ElseIf cboNomeOperacao.Value = "(+)Recebimento de pallet - transportadora" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!C2:C6"
lblMensagem.Caption = "Opção usada para registrar o recebimento/devolução do pallet 'emprestado'a transportadora"
ElseIf cboNomeOperacao.Value = "(-)Envio de pallet - outra unidade" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!D2:D6"
lblMensagem.Caption = "Opção usada para registrar o envio de pallet do Estoque Livre para outra unidade Leão"
ElseIf cboNomeOperacao.Value = "(+)Recebimento de pallet - outra unidade" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!D2:D6"
lblMensagem.Caption = "Opção usada para registrar o recebimento de pallet de outra unidade Leão para Estoque Livre"
ElseIf cboNomeOperacao.Value = "(-)Pallet em reforma do Estoque Livre" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar o pallet do Estqoue Livre que esta em reforma/conserto "
ElseIf cboNomeOperacao.Value = "(-)Pallet em reforma do Estoque em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar o pallet do Estoque em Rack/Drive que esta em reforma/conserto"
ElseIf cboNomeOperacao.Value = "(+)Pallet reformado do Estoque Livre" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar o pallet do Estoque Livre que ja foi reformado/consertado"
ElseIf cboNomeOperacao.Value = "(+)Pallet reformado do Estoque em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar o pallet do Estoque em Rack/Drive que ja foi reformado/consertado"
ElseIf cboNomeOperacao.Value = "(-)Descarte / Quebra do Estoque Livre" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!H1"
lblMensagem.Caption = "Opção usada para registrar o pallet do Estoque Livre quebrado ou descartado"
ElseIf cboNomeOperacao.Value = "(-)Descarte / Quebra do Estoque em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!H1"
lblMensagem.Caption = "Opção usada para registrar o pallet do Estoque em Rack/Drive quebrado ou descartado"
ElseIf cboNomeOperacao.Value = "(-)Movimento De Estoque Livre Para em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar a movimentação de pallet do Estoque Livre para o Rack/Drive"
ElseIf cboNomeOperacao.Value = "(+)Movimento De Estoque em Rack/Drive Para Livre" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar a movimentação de pallet do Estoque em Rack/Drive para o Livre "
ElseIf cboNomeOperacao.Value = "(+)Estoque inicial Livre para uso" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar estoque inicial de pallet de livre utilização "
ElseIf cboNomeOperacao.Value = "(+)Estoque inicial em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
cboIdentificacao.RowSource = "Dados!F1"
lblMensagem.Caption = "Opção usada para registrar estoque inicial de pallet em Rack/Drive "
End If
If cboNomeOperacao = "(-)Envio de pallet - cliente" Then
txtTransporte.Enabled = True
txtTransporte.BackColor = corEnabledTextBox
cboValePallet.Enabled = True
cboValePallet.BackColor = corEnabledTextBox
txtMotorista.Enabled = True
txtMotorista.BackColor = corEnabledTextBox
txtPlaca.Enabled = True
txtPlaca.BackColor = corEnabledTextBox
ElseIf cboNomeOperacao = "(-)Envio de pallet - outra unidade" Then
txtMotorista.Enabled = True
txtMotorista.BackColor = corEnabledTextBox
txtPlaca.Enabled = True
txtPlaca.BackColor = corEnabledTextBox
ElseIf cboNomeOperacao = "(+)Recebimento de pallet - outra unidade" Then
txtMotorista.Enabled = True
txtMotorista.BackColor = corEnabledTextBox
txtPlaca.Enabled = True
txtPlaca.BackColor = corEnabledTextBox
ElseIf cboNomeOperacao = "(+)Recebimento de pallet - cliente" Then
txtMotorista.Enabled = True
txtPlaca.Enabled = True
ElseIf cboNomeOperacao = "(-)Envio de pallet - transportadora" Then
txtTransporte.Enabled = True
txtTransporte.BackColor = corEnabledTextBox
cboValePallet.Enabled = True
cboValePallet.BackColor = corEnabledTextBox
txtMotorista.Enabled = True
txtMotorista.BackColor = corEnabledTextBox
txtPlaca.Enabled = True
txtPlaca.BackColor = corEnabledTextBox
ElseIf cboNomeOperacao = "(+)Recebimento de pallet - transportadora" Then
txtMotorista.Enabled = True
txtMotorista.BackColor = corEnabledTextBox
txtPlaca.Enabled = True
txtPlaca.BackColor = corEnabledTextBox
Else
txtMotorista.Enabled = False
txtMotorista.BackColor = corDisabledTextBox
txtMotorista.Value = ""
txtPlaca.Enabled = False
txtPlaca.BackColor = corDisabledTextBox
txtPlaca.Value = ""
txtTransporte.Enabled = False
txtTransporte.BackColor = corDisabledTextBox
txtTransporte.Value = ""
cboValePallet.Enabled = False
cboValePallet.BackColor = corDisabledTextBox
cboValePallet.Value = ""
End If
End Sub
Private Sub btnCancelar_Click()
btnOK.Enabled = False
btnCancelar.Enabled = False
Call DesabilitaControles
Call CarregaDadosInicial
Call HabilitaBotoesAlteracao
Call LimpaControles
End Sub
Private Sub btnOK_Click()
Dim proximoId As Long
'Altera
If optAlterar.Value Then
'Verifica se os campos estão vazios
If dtpDataRegistro.Value = "" Then
lblMensagem.Caption = "Digite uma data para o registro!"
dtpDataRegistro.SetFocus
ElseIf cboNomeOperacao.Value = "" Then
lblMensagem.Caption = "Selecione a Operação!"
cboNomeOperacao.SetFocus
ElseIf cboIdentificacao.Value = "" Then
lblMensagem.Caption = "Selecione a Identificação!"
cboIdentificacao.SetFocus
ElseIf txtQuantidade.Text = "" Then
lblMensagem.Caption = "Digite a quantidade!"
txtQuantidade.SetFocus
ElseIf cboConferencia.Value = "" Then
lblMensagem.Caption = "Selecione o responsavel pela conferencia!"
cboConferencia.SetFocus
ElseIf cboValePallet.Value = "" And cboValePallet.Enabled = True Then
lblMensagem.Caption = "Responda se tem Vale-Pallet!"
cboValePallet.SetFocus
Else
Call SalvaRegistro(CLng(txtCodigoRegistro.Text), indiceRegistro)
lblMensagem.Caption = "Registro salvo com sucesso!"
Call HabilitaBotoesAlteracao
Call DesabilitaControles
End If
End If
'Novo
If optNovo.Value Then
proximoId = PegaProximoId
'pega a próxima linha
Dim proximoIndice As Long
proximoIndice = wsCadastro.UsedRange.Rows.Count + 1
'Verifica se os campos estão vazios
If dtpDataRegistro.Value = "" Then
lblMensagem.Caption = "Digite uma data para o registro!"
dtpDataRegistro.SetFocus
ElseIf cboNomeOperacao.Value = "" Then
lblMensagem.Caption = "Selecione a Operação!"
cboNomeOperacao.SetFocus
ElseIf cboIdentificacao.Value = "" Then
lblMensagem.Caption = "Selecione a Identificação!"
cboIdentificacao.SetFocus
ElseIf txtQuantidade.Text = "" Then
lblMensagem.Caption = "Digite a quantidade!"
txtQuantidade.SetFocus
ElseIf cboValePallet.Text = "" And cboValePallet.Enabled = True Then
lblMensagem.Caption = "Responda se tem Vale-Pallet!"
dtpDataRegistro.SetFocus
ElseIf cboConferencia.Value = "" Then
lblMensagem.Caption = "Selecione o responsavel pela conferencia!"
cboConferencia.SetFocus
Else
Call SalvaRegistro(proximoId, proximoIndice)
txtCodigoRegistro = proximoId
lblMensagem.Caption = "Registro salvo com sucesso!"
Call HabilitaBotoesAlteracao
Call DesabilitaControles
End If
End If
'Excluir
If optExcluir.Value Then
Dim result As VbMsgBoxResult
result = MsgBox("Deseja excluir o registro nº " & txtCodigoRegistro.Text & " ?", vbYesNo, "Confirmação")
If result = vbYes Then
wsCadastro.Range(wsCadastro.Cells(indiceRegistro, colCodigoDoRegistro), wsCadastro.Cells(indiceRegistro, colCodigoDoRegistro)).EntireRow.Delete
Call CarregaDadosInicial
lblMensagem.Caption = "Registro excluído com sucesso!"
Call HabilitaBotoesAlteracao
Call DesabilitaControles
Call LimpaControles
End If
End If
End Sub
Private Sub btnPesquisar_Click()
Unload Me
frmPesquisa.Show
End Sub
Private Sub cmdMenu_Click()
frmCadastro.Hide
Sheets("capa").Activate
frmMenu.Show
End Sub

Private Sub optAlterar_Click()
If txtCodigoRegistro.Text <> vbNullString And txtCodigoRegistro.Text <> "" Then
Call HabilitaControles
Call DesabilitaBotoesAlteracao
'dá o foco ao primeiro controle de dados
dtpDataRegistro.SetFocus
Else
lblMensagem.Caption = "Não há registro a ser alterado"
Call LimpaControles
End If
End Sub
Private Sub optExcluir_Click()
If txtCodigoRegistro.Text <> vbNullString And txtCodigoRegistro.Text <> "" Then
Call DesabilitaBotoesAlteracao
lblMensagem.Caption = "Modo de exclusão. Confira o dados do registro antes de excluí-lo"
Else
lblMensagem.Caption = "Não há registro a ser excluído"
End If
End Sub
Private Sub optNovo_Click()
Call LimpaControles
Call HabilitaControles
Call DesabilitaBotoesAlteracao
'dá o foco ao primeiro controle de dados
dtpDataRegistro.SetFocus
End Sub
Private Sub txtTransporte_Change()
'Limita a Qde de caracteres
frmCadastro.txtTransporte.MaxLength = 6
frmCadastro.txtQuantidade.MaxLength = 5
frmCadastro.txtPlaca.MaxLength = 10
frmCadastro.txtMotorista.MaxLength = 20

End Sub
Private Sub UserForm_Initialize()
Set wsCadastro = ThisWorkbook.Worksheets("Registros")
Call HabilitaBotoesAlteracao
Call CarregaDadosInicial
Call DesabilitaControles
End Sub
Private Sub btnAnterior_Click()
If indiceRegistro > indiceMinimo Then
indiceRegistro = indiceRegistro - 1
End If
If indiceRegistro > 1 Then
Call CarregaRegistro
End If
End Sub
Private Sub btnPrimeiro_Click()
indiceRegistro = indiceMinimo
If indiceRegistro > 1 Then
Call CarregaRegistro
End If
End Sub
Private Sub btnProximo_Click()
If indiceRegistro < wsCadastro.UsedRange.Rows.Count Then
indiceRegistro = indiceRegistro + 1
End If
If indiceRegistro > 1 Then
Call CarregaRegistro
End If
End Sub
Private Sub btnUltimo_Click()
indiceRegistro = wsCadastro.UsedRange.Rows.Count
If indiceRegistro > 1 Then
Call CarregaRegistro
End If
End Sub
Private Sub CarregaDadosInicial()
indiceRegistro = 2
Call CarregaRegistro
End Sub
Private Sub CarregaRegistro()
'carrega os dados do primeiro registro
With wsCadastro
If Not IsEmpty(.Cells(indiceRegistro, colDeIdentificacao)) Then
Me.txtCodigoRegistro.Text = .Cells(indiceRegistro, colCodigoDoRegistro).Value
Me.dtpDataRegistro.Value = .Cells(indiceRegistro, colDataDoRegistro).Value
Me.cboNomeOperacao.Value = .Cells(indiceRegistro, colNomeDaOperacao).Value
Me.cboIdentificacao.Value = .Cells(indiceRegistro, colDeIdentificacao).Value
Me.txtTransporte.Text = .Cells(indiceRegistro, colNTransporte).Value
Me.txtQuantidade.Text = .Cells(indiceRegistro, colDeQuantidade).Value
Me.cboValePallet.Value = .Cells(indiceRegistro, colDeValePallet).Value
Me.cboConferencia.Value = .Cells(indiceRegistro, colDeConferencia).Value
Me.txtPlaca.Text = .Cells(indiceRegistro, colDePlaca).Value
Me.txtMotorista.Text = .Cells(indiceRegistro, colDeMotorista).Value
Me.txtObs.Text = .Cells(indiceRegistro, colDeObs).Value
End If
End With
Call AtualizaRegistroCorrente
End Sub
Public Sub CarregaRegistroPorIndice(ByVal indice As Long)
'carrega os dados do registro baseado no índice
indiceRegistro = indice
Call CarregaRegistro
End Sub
Private Sub SalvaRegistro(ByVal id As Long, ByVal indice As Long)
With wsCadastro
.Cells(indice, colCodigoDoRegistro).Value = id
.Cells(indice, colDataDoRegistro).Value = Me.dtpDataRegistro.Value
.Cells(indice, colNomeDaOperacao).Value = Me.cboNomeOperacao.Value
.Cells(indice, colDeIdentificacao).Value = Me.cboIdentificacao.Value
.Cells(indice, colNTransporte).Value = Me.txtTransporte.Text
.Cells(indice, colDeQuantidade).Value = Me.txtQuantidade.Text
.Cells(indice, colDeValePallet).Value = Me.cboValePallet.Value
.Cells(indice, colDeConferencia).Value = Me.cboConferencia.Value
.Cells(indice, colDePlaca).Value = Me.txtPlaca.Text
.Cells(indice, colDeMotorista).Value = Me.txtMotorista.Text
.Cells(indice, colDeObs).Value = Me.txtObs.Text
End With
Call AtualizaRegistroCorrente
End Sub
Private Function PegaProximoId() As Long
Dim rangeIds As Range
'pega o range que se refere a toda a coluna do código (id)
Set rangeIds = wsCadastro.Range(wsCadastro.Cells(indiceMinimo, colCodigoDoRegistro), wsCadastro.Cells(wsCadastro.UsedRange.Rows.Count, colCodigoDoRegistro))
PegaProximoId = WorksheetFunction.Max(rangeIds) + 1
End Function
Private Sub AtualizaRegistroCorrente()
lblNavigator.Caption = indiceRegistro - 1 & " de " & wsCadastro.UsedRange.Rows.Count - 1
lblMensagem.Caption = ""
End Sub
Private Sub LimpaControles()
Me.txtCodigoRegistro.Text = ""
Me.cboNomeOperacao.Value = ""
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
Me.txtTransporte.Text = ""
Me.txtQuantidade.Text = ""
Me.cboValePallet.Value = ""
Me.cboConferencia.Value = ""
Me.txtPlaca.Text = ""
Me.txtMotorista.Text = ""
Me.txtObs.Text = ""
End Sub
Private Sub HabilitaControles()
'Me.txtCodigoRegistro.Locked = False
Me.dtpDataRegistro.Enabled = True
Me.cboNomeOperacao.Locked = False
Me.cboIdentificacao.Locked = False
Me.txtTransporte.Locked = False
Me.txtQuantidade.Locked = False
Me.cboValePallet.Locked = False
Me.cboConferencia.Locked = False
Me.txtPlaca.Locked = False
Me.txtMotorista.Locked = False
Me.txtObs.Locked = False
Me.dtpDataRegistro.CalendarBackColor = corEnabledTextBox
Me.cboNomeOperacao.BackColor = corEnabledTextBox
Me.cboIdentificacao.BackColor = corEnabledTextBox
Me.txtTransporte.BackColor = corEnabledTextBox
Me.txtQuantidade.BackColor = corEnabledTextBox
Me.cboValePallet.BackColor = corEnabledTextBox
Me.cboConferencia.BackColor = corEnabledTextBox
Me.txtPlaca.BackColor = corEnabledTextBox
Me.txtMotorista.BackColor = corEnabledTextBox
Me.txtObs.BackColor = corEnabledTextBox
End Sub
Private Sub DesabilitaControles()
'Me.txtCodigoRegistro.Locked = True
Me.dtpDataRegistro.Enabled = False
Me.cboNomeOperacao.Locked = True
Me.cboIdentificacao.Locked = True
Me.txtTransporte.Locked = True
Me.txtQuantidade.Locked = True
Me.cboValePallet.Locked = True
Me.cboConferencia.Locked = True
Me.txtPlaca.Locked = True
Me.txtMotorista.Locked = True
Me.txtObs.Locked = True
Me.dtpDataRegistro.CalendarBackColor = corDisabledTextBox
Me.cboNomeOperacao.BackColor = corDisabledTextBox
Me.cboIdentificacao.BackColor = corDisabledTextBox
Me.txtTransporte.BackColor = corDisabledTextBox
Me.txtQuantidade.BackColor = corDisabledTextBox
Me.cboValePallet.BackColor = corDisabledTextBox
Me.cboConferencia.BackColor = corDisabledTextBox
Me.txtPlaca.BackColor = corDisabledTextBox
Me.txtMotorista.BackColor = corDisabledTextBox
Me.txtObs.BackColor = corDisabledTextBox
End Sub
Private Sub HabilitaBotoesAlteracao()
'habilita os botões de alteração
optAlterar.Enabled = True
optExcluir.Enabled = True
optNovo.Enabled = True
btnPesquisar.Enabled = True
btnOK.Enabled = False
btnCancelar.Enabled = False
'limpa os valores dos controles
optAlterar.Value = False
optExcluir.Value = False
optNovo.Value = False
End Sub
Private Sub DesabilitaBotoesAlteracao()
'desabilita os botões de alteração
optAlterar.Enabled = False
optExcluir.Enabled = False
optNovo.Enabled = False
btnPesquisar.Enabled = False
btnOK.Enabled = True
btnCancelar.Enabled = True
End Sub
Public Function ProcuraIndiceRegistroPodId(ByVal id As Long) As Long
Dim i As Long
Dim retorno As Long
Dim encontrado As Boolean
i = indiceMinimo
With wsCadastro
Do While Not IsEmpty(.Cells(i, colCodigoDoRegistro))
If .Cells(i, colCodigoDoRegistro).Value = id Then
retorno = i
encontrado = True
Exit Do
End If
i = i + 1
Loop
End With
'caso não encontre o registro, retorna -1
If Not encontrado Then
retorno = -1
End If
ProcuraIndiceRegistroPodId = i
End Function
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
Cancel = True
MsgBox "Ação não permitida", vbInformation
End If
End Sub


'Aplicativo de Cadastro de movimentação de pallet em VBA no Microsoft Excel: 'FORMULÁRIO DE PESQUISA'


Option Explicit

'constantes para auxiliar na verificação do código
Private Const Ascendente As Byte = 0
Private Const Descendente As Byte = 1

Private Sub btnCancelar_Click()
Call LimpaControles
End Sub
Private Sub cboNomeOperacao_Change()
If cboNomeOperacao.Value = "(-)Envio de pallet - cliente" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!B2:B68"
ElseIf cboNomeOperacao.Value = "(+)Recebimento de pallet - cliente" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!B2:B68"
ElseIf cboNomeOperacao.Value = "(-)Envio de pallet - transportadora" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!C2:C6"
ElseIf cboNomeOperacao.Value = "(+)Recebimento de pallet - transportadora" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!C2:C6"
ElseIf cboNomeOperacao.Value = "(-)Envio de pallet - outra unidade" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!D2:D6"
ElseIf cboNomeOperacao.Value = "(+)Recebimento de pallet - outra unidade" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!D2:D6"
ElseIf cboNomeOperacao.Value = "(-)Pallet em reforma do Estoque Livre" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(-)Pallet em reforma do Estoque em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(+)Pallet reformado do Estoque Livre" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(+)Pallet reformado do Estoque em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(-)Descarte / Quebra do Estoque Livre" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!H1"
ElseIf cboNomeOperacao.Value = "(-)Descarte / Quebra do Estoque em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!H1"
ElseIf cboNomeOperacao.Value = "(-)Movimento De Estoque Livre Para em Rack/Drive" Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(+)Movimento De Estoque em Rack/Drive Para Livre " Then
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(+)Estoque inicial Livre para uso " Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
ElseIf cboNomeOperacao.Value = "(+)Estoque inicial em Rack/Drive " Then
Me.cboIdentificacao.Value = ""
cboIdentificacao.RowSource = "Dados!F1"
End If
End Sub
Private Sub btnExportar_Click()
Call Exportar
Unload Me
End Sub
Private Sub btnFiltrar_Click()
Call PopulaListBox(dtpDataRegistro.Value, cboNomeOperacao.Value, txtTransporte.Text, cboIdentificacao.Value, cboValePallet.Value)
End Sub
Private Sub cmdMenu_Click()
frmPesquisa.Hide
Sheets("capa").Activate
frmMenu.Show
End Sub

Private Sub dtpDataRegistro_CallbackKeyDown(ByVal KeyCode As Integer, ByVal Shift As Integer, ByVal CallbackField As String, CallbackDate As Date)

End Sub

Private Sub lstLista_DblClick(ByVal Cancel As MSForms.ReturnBoolean)

If lstLista.ListIndex > 0 Then
Dim indiceRegistro As Long
indiceRegistro = frmCadastro.ProcuraIndiceRegistroPodId(lstLista.List(lstLista.ListIndex, 0))
If indiceRegistro <> -1 Then
Call frmCadastro.CarregaRegistroPorIndice(indiceRegistro)
End If
frmPesquisa.Hide
frmCadastro.Show
Else
lblMensagens.Caption = "É preciso selecionar um item válido na lista"
End If
End Sub
Private Sub UserForm_Initialize()
'preenche o cboDirecao e seleciona o primeiro item
cboDirecao.Clear
cboDirecao.AddItem "Ascendente"
cboDirecao.AddItem "Descendente"
cboDirecao.ListIndex = 0
Call PopulaListBox(vbNullString, vbNullString, vbNullString, vbNullString, vbNullString)
End Sub
Private Sub Exportar()
Dim i As Integer
Dim NewWorkBook As Workbook
Dim rst As ADODB.Recordset
' Preenche o RecordSet com os filtros atuais
Set rst = PreecheRecordSet(dtpDataRegistro.Value, cboNomeOperacao.Value, txtTransporte.Text, cboIdentificacao.Value, cboValePallet.Value)
'cria um novo Workbook
Set NewWorkBook = Application.Workbooks.Add
' Efetua loop em todos os campos, retornando os nomes de campos
' à planilha.
For i = 0 To rst.Fields.Count - 1
NewWorkBook.Sheets(1).Range("A1").Offset(0, i).Value = rst.Fields(i).Name
Next i

NewWorkBook.Sheets(1).Range("A2").CopyFromRecordset rst
NewWorkBook.Activate
End Sub

Private Sub PopulaListBox(ByVal DataRegistro As String, _
ByVal NomeOperacao As String, _
ByVal Identificacao As String, _
ByVal Transporte As String, _
ByVal ValePallet As String)

On Error GoTo TrataErro

Dim rst As ADODB.Recordset
Dim Campo As Field
Dim myArray() As Variant
Dim i As Integer

Set rst = PreecheRecordSet(DataRegistro, NomeOperacao, Identificacao, Transporte, ValePallet)

'pega o número de registros para atribuí-lo ao listbox
lstLista.ColumnCount = rst.Fields.Count

'preenche o combobox com os nomes dos campos
'persiste o índice
Dim indiceTemp As Long
indiceTemp = cboOrdenarPor.ListIndex
cboOrdenarPor.Clear
For Each Campo In rst.Fields
cboOrdenarPor.AddItem Campo.Name
Next
'recupera o índice selecionado
cboOrdenarPor.ListIndex = indiceTemp

'coloca as linhas do RecordSet num Array, se houver linhas neste
If Not rst.EOF And Not rst.BOF Then
myArray = rst.GetRows
'troca linhas por colunas no Array
myArray = Array2DTranspose(myArray)
'atribui o Array ao listbox
lstLista.List = myArray
'adiciona a linha de cabeçalho da coluna
lstLista.AddItem , 0
'preenche o cabeçalho
For i = 0 To rst.Fields.Count - 1
lstLista.List(0, i) = rst.Fields(i).Name
Next i
'seleciona o primeiro item da lista
lstLista.ListIndex = 0
Else
lstLista.Clear
End If

'atualiza o label de mensagens
If lstLista.ListCount <= 0 Then
lblMensagens.Caption = lstLista.ListCount & " registros encontrados"
Else
lblMensagens.Caption = lstLista.ListCount - 1 & " registros encontrados"
End If

' Fecha o conjunto de registros.
Set rst = Nothing
' Fecha a conexão.
'conn.Close

TrataSaida:
Exit Sub
TrataErro:
Debug.Print Err.Description & vbNewLine & Err.Number & vbNewLine & Err.Source
Resume TrataSaida
End Sub

Private Function PreecheRecordSet(ByVal DataRegistro As String, _
ByVal NomeOperacao As String, _
ByVal dentificacao As String, _
ByVal Transporte As String, _
ByVal ValePallet As String) As Recordset
On Error GoTo TrataErro

Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sql As String
Dim sqlWhere As String
Dim sqlOrderBy As String
Dim i As Integer
Dim Campo As Field
Dim myArray() As Variant

Set conn = New ADODB.Connection
With conn
.Provider = "Microsoft.JET.OLEDB.4.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";Extended Properties=Excel 8.0;"
.Open
End With

sql = "SELECT * FROM [Registros$]"

'monta a cláusula WHERE
'DataDoRegistro
Call MontaClausulaWhere(dtpDataRegistro.Name, "DataRegistro", sqlWhere)

'NomeOperacao
Call MontaClausulaWhere(cboNomeOperacao.Name, "NomeDaOperacao", sqlWhere)

'Transporte
Call MontaClausulaWhere(txtTransporte.Name, "Identificacao", sqlWhere)

'Identificacao
Call MontaClausulaWhere(cboIdentificacao.Name, "Transporte", sqlWhere)

'vale pallet
Call MontaClausulaWhere(cboValePallet.Name, "ValePallet", sqlWhere)

'faz a união da string SQL com a cláusula WHERE
If sqlWhere <> vbNullString Then
sql = sql & " WHERE " & sqlWhere
End If

'faz a união da string SQL com a cláusula ORDER BY
If cboOrdenarPor.ListIndex <> -1 Then
sqlOrderBy = " ORDER BY " & cboOrdenarPor.List(cboOrdenarPor.ListIndex, 0)
'define a direção
Select Case cboDirecao.ListIndex
Case Ascendente
sqlOrderBy = sqlOrderBy & " ASC"
Case Descendente
sqlOrderBy = sqlOrderBy & " DESC"
End Select
'une a query order ao sql
sql = sql & sqlOrderBy
End If

Set rst = New ADODB.Recordset
rst.CursorLocation = adUseClient
With rst
.ActiveConnection = conn
.Open sql, conn, adOpenForwardOnly, _
adLockBatchOptimistic
End With

Set rst.ActiveConnection = Nothing

' Fecha a conexão.
conn.Close

Set PreecheRecordSet = rst
Exit Function
TrataErro:
Set rst = Nothing
End Function

Private Sub MontaClausulaWhere(ByVal NomeControle As String, ByVal NomeCampo As String, ByRef sqlWhere As String)
'Identificacao
If Trim(Me.Controls(NomeControle).Text) <> vbNullString Then
If sqlWhere <> vbNullString Then
sqlWhere = sqlWhere & " AND"
End If
sqlWhere = sqlWhere & " UCASE(" & NomeCampo & ") LIKE UCASE('%" & Trim(Me.Controls(NomeControle).Text) & "%')"
End If
End Sub

'Faz a transpasição de um array, transformando linhas em colunas
Private Function Array2DTranspose(avValues As Variant) As Variant
Dim lThisCol As Long, lThisRow As Long
Dim lUb2 As Long, lLb2 As Long
Dim lUb1 As Long, lLb1 As Long
Dim avTransposed As Variant

If IsArray(avValues) Then
On Error GoTo ErrFailed
lUb2 = UBound(avValues, 2)
lLb2 = LBound(avValues, 2)
lUb1 = UBound(avValues, 1)
lLb1 = LBound(avValues, 1)

ReDim avTransposed(lLb2 To lUb2, lLb1 To lUb1)
For lThisCol = lLb1 To lUb1
For lThisRow = lLb2 To lUb2
avTransposed(lThisRow, lThisCol) = avValues(lThisCol, lThisRow)
Next
Next
End If

Array2DTranspose = avTransposed
Exit Function

ErrFailed:
Debug.Print Err.Description
Debug.Assert False
Array2DTranspose = Empty
Exit Function
Resume
End Function
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)

If CloseMode = 0 Then
Cancel = True
MsgBox "Ação não permitida", vbInformation
End If

End Sub
Private Sub LimpaControles()

Me.cboNomeOperacao.Value = ""
Me.cboIdentificacao.Value = ""
Me.cboIdentificacao.RowSource = ""
Me.txtTransporte.Text = ""
Me.cboValePallet.Value = ""
Me.cboOrdenarPor.Value = ""
Me.cboDirecao.Value = ""

End Sub

mauribeiro82

09-10-2014 16:59:20

Olá pessoal! Alguém me ajude por favor...planilha em anexo.

Edilson_RO

08-01-2015 20:45:59

Baixei essa mesma planilha, aqui o problema foi na hora de cadastrar um NOVO cliente. Grava na planilha mas não grava no formulário do VBA, aparentemente grava mas depois some, acredito q seja algo relacionado ao envento do botão on click mas não descobri.