Não pula linha em novo registro

vinicius_i

24-12-2010 02:25:28

Boa noite,

Estou adaptando a planilha de cadastro V3 com mais de 1 BD, igual o modelo que o Mauro postou.
O problema que estou enfrentado é na hora de lançar um novo registro, que em vez dele pular uma linha e lançar, ele simplesmente está substituindo os antigos registros e também se eu lançar mais de um registro manualmente na planilha, ele acaba apagando esses registros e substituindo tudo pelo o que registrei pelo VBA.

Se alguem puder me ajudar, desde já agradeço.

Segue código:

Código: Selecionar todos

'Modelo de Aplicativo de Cadastro em VBA no Microsoft Excel
'Autor: Tomás Vásquez
'http://www.tomasvasquez.com.br
'http://tomas.vasquez.blog.uol.com.br
'março de 2008

Option Explicit

Const colCodigoDoFornecedor As Integer = 1
Const colSgrupo As Integer = 2

Const indiceMinimo As Byte = 2
Const corDisabledTextBox As Long = -2147483633
Const corEnabledTextBox As Long = -2147483643

Private indiceRegistro As Long

Private Sub btnCancelar_Click()
    btnok.Enabled = False
    btncancelar.Enabled = False
    Call DesabilitaControles
    Call CarregaDadosInicial
    Call HabilitaBotoesAlteracao
End Sub

Private Sub btnOk_Click()
    Dim proximoId As Long

    'Altera
    If optalterar.Value Then
        Call SalvaRegistro(CLng(txtCodigoFornecedor.Text), indiceRegistro)
        lblMensagem.Caption = "Registro salvo com sucesso"
    End If
    'Novo
    If optnovo.Value Then
        proximoId = PegaProximoId
        'pega a próxima linha
        Dim proximoIndice As Long
        'atualiza o arquivo para pegar o próximo registro atualizado
        Call AtualizarArquivo(False)
        proximoIndice = wsSgrupo.UsedRange.Rows.Count + 1
        Call SalvaRegistro(proximoId, proximoIndice)
        txtCodigoFornecedor = proximoId
        lblMensagem.Caption = "Registro salvo com sucesso"
    End If
    'Excluir
    If optexcluir.Value Then
        Dim result As VbMsgBoxResult
        result = MsgBox("Deseja excluir o registro nº " & txtCodigoFornecedor.Text & " ?", vbYesNo, "Confirmação")

        If result = vbYes Then
            'abre o arquivo para escrita
            Call AtualizarArquivo(False)
            wsSgrupo.Range(wsSgrupo.Cells(indiceRegistro, colCodigoDoFornecedor), wsSgrupo.Cells(indiceRegistro, colCodigoDoFornecedor)).EntireRow.Delete
            'salva
            wbCadastro.Save
            'abre somente leitura
            Call AtualizarArquivo(True)
            Call CarregaDadosInicial
            lblMensagem.Caption = "Registro excluído com sucesso"
        End If
    End If

    Call HabilitaBotoesAlteracao
    Call DesabilitaControles

End Sub

Private Sub btnPesquisar_Click()
    frmPesquisa.Show
End Sub


Private Sub optAlterar_Click()
    If txtCodigoFornecedor.Text <> vbNullString And txtCodigoFornecedor.Text <> "" Then
        Call HabilitaControles
        Call DesabilitaBotoesAlteracao
        'dá o foco ao primeiro controle de dados
        txt_sgrupo.SetFocus
    Else
        lblMensagem.Caption = "Não há registro a ser alterado"
    End If
End Sub

Private Sub optExcluir_Click()
    If txtCodigoFornecedor.Text <> vbNullString And txtCodigoFornecedor.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
    txt_sgrupo.SetFocus
End Sub

Private Sub UserForm_Initialize()
        
    Call DefinePlanilhaDados
    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 < wsSgrupo.UsedRange.Rows.Count Then
        indiceRegistro = indiceRegistro + 1
    End If
    If indiceRegistro > 1 Then
        Call CarregaRegistro
    End If
End Sub

Private Sub btnUltimo_Click()
    indiceRegistro = wsSgrupo.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 wsSgrupo
        If Not IsEmpty(.Cells(indiceRegistro, colCodigoDoFornecedor)) Then
            Me.txtCodigoFornecedor.Text = .Cells(indiceRegistro, colCodigoDoFornecedor).Value
            Me.txt_sgrupo.Text = .Cells(indiceRegistro, colSgrupo).Text

        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 AtualizarArquivo(ByVal ReadOnly As Boolean)
    Dim caminhoCompleto As String
    'fecha o arquivo de dados e tenta abrí-lo
    'guarda o caminho
    caminhoCompleto = wbCadastro.FullName
    wbCadastro.Saved = True
    wbCadastro.Close SaveChanges:=False
    

    'abre o arquivo em modo escrita
    Set wbCadastro = Workbooks.Open(Filename:=caminhoCompleto, ReadOnly:=ReadOnly)
    
    'oculta a janela
    wbCadastro.Windows(1).Visible = False
    
    'reatribui a planilha de cadastro
    Set wsSgrupo = wbCadastro.Worksheets(nomePlanilhaSgrupo)
End Sub

Private Sub SalvaRegistro(ByVal id As Long, ByVal indice As Long)
    'tenta abrir o arquivo em modo escrita
    Call AtualizarArquivo(False)
    
    With wsSgrupo
        .Cells(indice, colCodigoDoFornecedor).Value = id
        .Cells(indice, colSgrupo).Value = Me.txt_sgrupo.Text

    End With
    
    'salva o arquivo
    Call wbCadastro.Save
    
    'abre o arquivo novamente em modo leitura
    Call AtualizarArquivo(True)

    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 = wsSgrupo.Range(wsSgrupo.Cells(indiceMinimo, colCodigoDoFornecedor), wsSgrupo.Cells(wsSgrupo.UsedRange.Rows.Count, colCodigoDoFornecedor))
    PegaProximoId = WorksheetFunction.Max(rangeIds) + 1
End Function

Private Sub AtualizaRegistroCorrente()
    lblNavigator.Caption = indiceRegistro - 1 & " de " & wsSgrupo.UsedRange.Rows.Count - 1
    lblMensagem.Caption = ""
End Sub

Private Sub LimpaControles()
    Me.txtCodigoFornecedor.Text = ""
    Me.txt_sgrupo.Text = ""

   
End Sub

Private Sub HabilitaControles()
'Me.txtCodigoFornecedor.Locked = False
    Me.txt_sgrupo.Locked = False


    Me.txt_sgrupo.BackColor = corEnabledTextBox


End Sub

Private Sub DesabilitaControles()
'Me.txtCodigoFornecedor.Locked = True
    Me.txt_sgrupo.Locked = True

    
    Me.txt_sgrupo.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 wsSgrupo
        Do While Not IsEmpty(.Cells(i, colCodigoDoFornecedor))
            If .Cells(i, colCodigoDoFornecedor).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)
    'fecha a planilha de dados, se estiver aberta
    If Not wbCadastro Is Nothing Then
        wbCadastro.Saved = True
        wbCadastro.Close SaveChanges:=False
    End If
        
    Set wbCadastro = Nothing
End Sub

Mauro Coutinho

24-12-2010 02:49:36

Vinicius, eu já havia me comprometido em dar uma olhada neste Bug, pois não é o primeiro tópico, mas até o momento não tive tempo hábil, mas o nosso colega Fabricio postou uma solução com as alterações que ele cita no Tópico abaixo, de uma olhada faça as alterações e depois retorne os resultados.
Lembre-se de na pasta Dados limpa todas as formataçoes.

viewtopic.php?f=5&t=651

[]s

vinicius_i

28-12-2010 05:07:05

Obrigado pela atenção Mauro.

Tentei usar a dica do Fabricio mas não deu certo, vou continuar usando a V2 mesmo.

lokaumz

28-12-2010 11:08:51

Bom dia vinicius..

Como posso lhe ajudar?

Mauro Coutinho

28-12-2010 15:50:07

Vinicius, como realizou adaptações, o ideal seria analizar o seu modelo e não somente as rotinas, mas nos teste que cheguei a fazer no modelo original usando a dica do Fabricio funcionou corretamente.
Lembre-se que a planilha que recebe os Dados tem de estar com a formatação limpa, ou seja, se editar e simplesmente deletar alguns dados mas manter a formatações da celula, a rotina de lançamento reconhece como celulas preenchidas.
[]s