SQL ADO - Código

Abrindo o Banco de Dados

Crie um Módulo e a declare a variável:
Public cnn As New ADODB.Connection

Crie a sub main, digitando Sub Main seguido de Enter e coloque o código abaixo, devendo a rotina ficar assim:

Sub Main()
cnn.Open "Provider=SQLOLEDB.1;User ID=sa;Initial Catalog=CadCli;Data Source=EDSON"
cnn.CursorLocation = adUseServer
frmCadCli.Show vbModal
End Sub

Botão Novo

Call Limpar
Dim sSQL As String
sSQL = "Select Max(Codigo) as MaxCliente From Clientes" 'Obtém o número do maior código
Set rsCliente = cnn.Execute(sSQL) 'Executa para filtrar a linha acima
If Not rsCliente.EOF Then 'Se achou, soma mais um para obter o próximo código
mskCodigo.Text = Val(rsCliente!MaxCliente) + 1
Else 'Caso contrário
mskCodigo.Text = 1 'É porque a tabela está vazia, e se iniciará o código a partir do 1
End If
rsCliente.Close
Set rsCliente = Nothing
cmdNovo.Enabled = False
cmdExcluir.Enabled = False
cmdSalvar.Enabled = True
txtNome.SetFocus

Botão Salvar

If MsgBox("Deseja Salvar", vbYesNo + vbQuestion, "Salvar") = vbYes Then
If mskCodigo.Text = "" Then
MsgBox "Informe o Código", vbInformation, "Código"
mskCodigo.SetFocus 'Envia o foco para o textbox
Exit Sub 'Não executa as linhas abaixo
End If

'Senão for digitado o nome então
If txtNome.Text = "" Then
MsgBox "Informe o Nome", vbInformation, "Nome"
txtNome.SetFocus 'Envia o foco para o textbox
Exit Sub 'Não executa as linhas abaixo
End If

On Error GoTo Erro_Salvar

Dim sSQL As String
sSQL = "Select * From Clientes Where Codigo=" & Val(mskCodigo.Text)
Set rsCliente = cnn.Execute(sSQL)
If Not rsCliente.EOF Then

sSQL = "Update Cliente Set Nome='" & txtNome.Text
sSQL = sSQL & "', Cidade='" & txtCidade.Text
sSQL = sSQL & "', Estado='" & txtEstado.Text
sSQL = sSQL & "', Cep='" & mskCEP.Text
sSQL = sSQL & "', TelefoneResidencial='" & mskTelefone.Text
Else
sSQL = "Insert Into Clientes (Codigo, Nome, Cidade, Estado, Cep, Telefone)"
sSQL = sSQL & "Values (" & txtCodigo.Text & ","
sSQL = sSQL & "'" & txtNome.Text & "'" & ","
sSQL = sSQL & "'" & txtCidade.Text & "'" & ","
sSQL = sSQL & "'" & mskCEP.Text & "'" & ","
sSQL = sSQL & "'" & mskTelefone.Text & "'" & ","
End If
Cnn.Execute (sSQL)
rsCliente.Close
Set rsCliente = Nothing
End If 'Fecha o End If
mskCodigo.SetFocus
cmdNovo.Enabled = True
cmdExcluir.Enabled = False
cmdSalvar.Enabled = False
Exit Sub
Erro_Salvar:
MsgBox Err.Number & Chr(13) & Err.Description
cmdNovo.Enabled = True
cmdSalvar.Enabled = False

Botão Excluir

If MsgBox("Deseja Excluir", vbYesNo + vbQuestion, "Excluir") = vbYes Then
On Error GoTo Excluir
Dim sSQL As String
sSQL = "Delete * From Clientes Where Codigo=" & Val(mskCodigo.Text)
Cnn.Execute (sSQL)
rsCliente.Close
Set rsCliente = Nothing
cmdSalvar.Enabled = False
cmdExcluir.Enabled = False
Call Limpar
End If
mskCodigo.SetFocus
Exit Sub
Excluir:
MsgBox Err.Number & Chr(13) & Err.Description

Hosted by www.Geocities.ws

1