eric
17-09-2011 00:07:21
Prezados senhoras, assim como eu vários desejam utilizar ou utilizaram o modelo do prezado ricardo horta para adaptar as suas necessidades. Ocorre que para altera-lo exige-se um pouquinho mais de conhecimento.
Solicito a quem puder e querer explique o código de forma didática para leigos que tenham uma certa afinidade com informática.
Pode ser por blocos.
grato a quem ajudar.
O ideal seria que o próprio ricardo explicasse pois já que ele foi quem fez poderia fazer isso com rapidez.
Estou fazendo um manual de linhas de códigos para auxiliar aos que como não não fez curso, mas por pesquisar olhando os códigos consegue aprender algumas coisas.
P.s. tentei enviar a planilha mas o site não permitiu. diga seu e-mail que lhe envio.






























e da pesquisa
Solicito a quem puder e querer explique o código de forma didática para leigos que tenham uma certa afinidade com informática.
Pode ser por blocos.
grato a quem ajudar.
O ideal seria que o próprio ricardo explicasse pois já que ele foi quem fez poderia fazer isso com rapidez.
Estou fazendo um manual de linhas de códigos para auxiliar aos que como não não fez curso, mas por pesquisar olhando os códigos consegue aprender algumas coisas.
P.s. tentei enviar a planilha mas o site não permitiu. diga seu e-mail que lhe envio.
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 colNomeDaEmpresa As Integer = 2
Const colNomeDoContato As Integer = 3
Const colCargoDoContato As Integer = 4
Const colEndereco As Integer = 5
Const colCidade As Integer = 6
Const colRegiao As Integer = 7
Const colCEP As Integer = 8
Const colPais As Integer = 9
Const colTelefone As Integer = 10
Const colFax As Integer = 11
Const colHomePage As Integer = 12
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 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
proximoIndice = wsCadastro.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
wsCadastro.Range(wsCadastro.Cells(indiceRegistro, colCodigoDoFornecedor), wsCadastro.Cells(indiceRegistro, colCodigoDoFornecedor)).EntireRow.Delete
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
txtNomeEmpresa.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
txtNomeEmpresa.SetFocus
End Sub
Private Sub UserForm_Initialize()
Set wsCadastro = ThisWorkbook.Worksheets("Fornecedores")
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, colCargoDoContato)) Then
Me.txtCodigoFornecedor.Text = .Cells(indiceRegistro, colCodigoDoFornecedor).Value
Me.txtNomeEmpresa.Text = .Cells(indiceRegistro, colNomeDaEmpresa).Value
Me.txtNomeContato.Text = .Cells(indiceRegistro, colNomeDoContato).Value
Me.txtCargoContato.Text = .Cells(indiceRegistro, colCargoDoContato).Value
Me.txtEndereco.Text = .Cells(indiceRegistro, colEndereco).Value
Me.txtCidade.Text = .Cells(indiceRegistro, colCidade).Value
Me.txtRegiao.Text = .Cells(indiceRegistro, colRegiao).Value
Me.txtCEP.Text = .Cells(indiceRegistro, colCEP).Value
Me.txtPais.Text = .Cells(indiceRegistro, colPais).Value
Me.txtTelefone.Text = .Cells(indiceRegistro, colTelefone).Value
Me.txtFax.Text = .Cells(indiceRegistro, colFax).Value
Me.txtHomePage.Text = .Cells(indiceRegistro, colHomePage).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, colCodigoDoFornecedor).Value = id
.Cells(indice, colNomeDaEmpresa).Value = Me.txtNomeEmpresa.Text
.Cells(indice, colNomeDoContato).Value = Me.txtNomeContato.Text
.Cells(indice, colCargoDoContato).Value = Me.txtCargoContato.Text
.Cells(indice, colEndereco).Value = Me.txtEndereco.Text
.Cells(indice, colCidade).Value = Me.txtCidade.Text
.Cells(indice, colRegiao).Value = Me.txtRegiao.Text
.Cells(indice, colCEP).Value = Me.txtCEP.Text
.Cells(indice, colPais).Value = Me.txtPais.Text
.Cells(indice, colTelefone).Value = Me.txtTelefone.Text
.Cells(indice, colFax).Value = Me.txtFax.Text
.Cells(indice, colHomePage).Value = Me.txtHomePage.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, colCodigoDoFornecedor), wsCadastro.Cells(wsCadastro.UsedRange.Rows.Count, colCodigoDoFornecedor))
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.txtCodigoFornecedor.Text = ""
Me.txtNomeEmpresa.Text = ""
Me.txtNomeContato.Text = ""
Me.txtCargoContato.Text = ""
Me.txtEndereco.Text = ""
Me.txtCidade.Text = ""
Me.txtRegiao.Text = ""
Me.txtCEP.Text = ""
Me.txtPais.Text = ""
Me.txtTelefone.Text = ""
Me.txtFax.Text = ""
Me.txtHomePage.Text = ""
End Sub
Private Sub HabilitaControles()
'Me.txtCodigoFornecedor.Locked = False
Me.txtNomeEmpresa.Locked = False
Me.txtNomeContato.Locked = False
Me.txtCargoContato.Locked = False
Me.txtEndereco.Locked = False
Me.txtCidade.Locked = False
Me.txtRegiao.Locked = False
Me.txtCEP.Locked = False
Me.txtPais.Locked = False
Me.txtTelefone.Locked = False
Me.txtFax.Locked = False
Me.txtHomePage.Locked = False
Me.txtNomeEmpresa.BackColor = corEnabledTextBox
Me.txtNomeContato.BackColor = corEnabledTextBox
Me.txtCargoContato.BackColor = corEnabledTextBox
Me.txtEndereco.BackColor = corEnabledTextBox
Me.txtCidade.BackColor = corEnabledTextBox
Me.txtRegiao.BackColor = corEnabledTextBox
Me.txtCEP.BackColor = corEnabledTextBox
Me.txtPais.BackColor = corEnabledTextBox
Me.txtTelefone.BackColor = corEnabledTextBox
Me.txtFax.BackColor = corEnabledTextBox
Me.txtHomePage.BackColor = corEnabledTextBox
End Sub
Private Sub DesabilitaControles()
'Me.txtCodigoFornecedor.Locked = True
Me.txtNomeEmpresa.Locked = True
Me.txtNomeContato.Locked = True
Me.txtCargoContato.Locked = True
Me.txtEndereco.Locked = True
Me.txtCidade.Locked = True
Me.txtRegiao.Locked = True
Me.txtCEP.Locked = True
Me.txtPais.Locked = True
Me.txtTelefone.Locked = True
Me.txtFax.Locked = True
Me.txtHomePage.Locked = True
Me.txtNomeEmpresa.BackColor = corDisabledTextBox
Me.txtNomeContato.BackColor = corDisabledTextBox
Me.txtCargoContato.BackColor = corDisabledTextBox
Me.txtEndereco.BackColor = corDisabledTextBox
Me.txtCidade.BackColor = corDisabledTextBox
Me.txtRegiao.BackColor = corDisabledTextBox
Me.txtCEP.BackColor = corDisabledTextBox
Me.txtPais.BackColor = corDisabledTextBox
Me.txtTelefone.BackColor = corDisabledTextBox
Me.txtFax.BackColor = corDisabledTextBox
Me.txtHomePage.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, 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
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
'constantes para auxiliar na verificação do código
Private Const Ascendente As Byte = 0
Private Const Descendente As Byte = 1
Private Sub btnExportar_Click()
Call Exportar
End Sub
Private Sub btnFiltrar_Click()
Call PopulaListBox(txtNomeEmpresa.Text, txtNomeContato.Text, txtEndereco.Text, txtTelefone.Text, txtRegiao.Text)
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
Unload Me
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 PopulaCidades
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(txtNomeEmpresa.Text, txtNomeContato.Text, txtEndereco.Text, txtTelefone.Text, txtRegiao.Text)
'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 PopulaCidades()
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sql As String
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 DISTINCT Cidade FROM [Fornecedores$]"
Set rst = New ADODB.Recordset
With rst
.ActiveConnection = conn
.Open sql, conn, adOpenDynamic, _
adLockBatchOptimistic
End With
Do While Not rst.EOF
If Not IsNull(rst(0).Value) Then
lstCidades.AddItem rst(0).Value
End If
rst.MoveNext
Loop
' Fecha o conjunto de registros.
Set rst = Nothing
' Fecha a conexão.
conn.Close
End Sub
Private Sub PopulaListBox(ByVal NomeEmpresa As String, _
ByVal NomeContato As String, _
ByVal Endereco As String, _
ByVal Telefone As String, _
ByVal Regiao 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(NomeEmpresa, NomeContato, Endereco, Telefone, Regiao)
'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 NomeEmpresa As String, _
ByVal NomeContato As String, _
ByVal Endereco As String, _
ByVal Telefone As String, _
ByVal Regiao 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 [Fornecedores$]"
'monta a cláusula WHERE
'NomeDaEmpresa
Call MontaClausulaWhere(txtNomeEmpresa.Name, "NomeDaEmpresa", sqlWhere)
'NomeDoContato
Call MontaClausulaWhere(txtNomeContato.Name, "NomeDoContato", sqlWhere)
'Endereço
Call MontaClausulaWhere(txtEndereco.Name, "Endereço", sqlWhere)
'Cidade
For i = 1 To lstCidades.ListCount
'verifica se o item está selecionado
If lstCidades.Selected(i - 1) Then
'Monta a cláusula WHERE com OR
Debug.Print lstCidades.List(i - 1) & " selecionado"
If sqlWhere <> vbNullString Then
sqlWhere = sqlWhere & " OR"
End If
sqlWhere = sqlWhere & " UCASE(Cidade) LIKE UCASE('%" & Trim(lstCidades.List(i - 1)) & "%')"
End If
Next
'Telefone
Call MontaClausulaWhere(txtTelefone.Name, "Telefone", sqlWhere)
'Região
Call MontaClausulaWhere(txtRegiao.Name, "Região", 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)
'NomeDoContato
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