Bom dia Mikel,
Vou disponibilizar toda a linha de comando que dá erro abaixo:
Essa é a parte que clico no botão pesquisar e dá erro, ai clico em depurar e me aparece isso.
BtnPesquisar, que está dentro do do fmCadastro:
'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
'Adaptação Mauro Coutinho com LISTVIEW
'Julho de 2011
Option Explicit
Const colCodigoDoFornecedor As Integer = 1
Const colNomeDaEmpresa As Integer = 2
Const colCNPJ As Integer = 3
Const colFone As Integer = 4
Const colContato As Integer = 5
Const colProduto As Integer = 6
Const colEmail As Integer = 7
Const colValorCotado As Integer = 8
Const colRegiao As Integer = 9
Const colOutrosProdutos As Integer = 10
Const colSkype As Integer = 11
Const colHomePage As Integer = 12
Const indiceMinimo As Byte = 2
Const corDisabledTextBox As Long = -2147483633
Const corEnabledTextBox As Long = -2147483643
Const nomePlanilhaCadastro As String = "Fornecedores"
Private wsCadastro As Worksheet
Private wbCadastro As Workbook
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 = 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
'abre o arquivo para escrita
Call AtualizarArquivo(False)
wsCadastro.Range(wsCadastro.Cells(indiceRegistro, colCodigoDoFornecedor), wsCadastro.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
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()
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 < 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, colCodigoDoFornecedor)) Then
Me.txtCodigoFornecedor.Text = .Cells(indiceRegistro, colCodigoDoFornecedor).Value
Me.txtNomeEmpresa.Text = .Cells(indiceRegistro, colNomeDaEmpresa).Value
Me.txtCNPJ.Text = .Cells(indiceRegistro, colCNPJ).Value
Me.txtFone.Text = .Cells(indiceRegistro, colFone).Value
Me.txtContato.Text = .Cells(indiceRegistro, colContato).Value
Me.txtProduto.Text = .Cells(indiceRegistro, colProduto).Value
Me.txtEmail.Text = .Cells(indiceRegistro, colEmail).Value
Me.txtValorCotado.Text = .Cells(indiceRegistro, colValorCotado).Value
Me.txtRegiao.Text = .Cells(indiceRegistro, colRegiao).Value
Me.txtOutrosProdutos.Text = .Cells(indiceRegistro, colOutrosProdutos).Value
Me.txtSkype.Text = .Cells(indiceRegistro, colSkype).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 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 wsCadastro = wbCadastro.Worksheets(nomePlanilhaCadastro)
End Sub
Private Sub SalvaRegistro(ByVal id As Long, ByVal indice As Long)
'tenta abrir o arquivo em modo escrita
Call AtualizarArquivo(False)
With wsCadastro
.Cells(indice, colCodigoDoFornecedor).Value = id
.Cells(indice, colNomeDaEmpresa).Value = Me.txtNomeEmpresa.Text
.Cells(indice, colCNPJ).Value = Me.txtCNPJ.Text
.Cells(indice, colFone).Value = Me.txtFone.Text
.Cells(indice, colContato).Value = Me.txtContato.Text
.Cells(indice, colProduto).Value = Me.txtProduto.Text
.Cells(indice, colEmail).Value = Me.txtEmail.Text
.Cells(indice, colValorCotado).Value = Me.txtValorCotado.Text
.Cells(indice, colRegiao).Value = Me.txtRegiao.Text
.Cells(indice, colOutrosProdutos).Value = Me.txtOutrosProdutos.Text
.Cells(indice, colSkype).Value = Me.txtSkype.Text
.Cells(indice, colHomePage).Value = Me.txtHomePage.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 = 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.txtCNPJ.Text = ""
Me.txtFone.Text = ""
Me.txtContato.Text = ""
Me.txtProduto.Text = ""
Me.txtEmail.Text = ""
Me.txtValorCotado.Text = ""
Me.txtRegiao.Text = ""
Me.txtOutrosProdutos.Text = ""
Me.txtSkype.Text = ""
Me.txtHomePage.Text = ""
End Sub
Private Sub HabilitaControles()
'Me.txtCodigoFornecedor.Locked = False
Me.txtNomeEmpresa.Locked = False
Me.txtCNPJ.Locked = False
Me.txtFone.Locked = False
Me.txtContato.Locked = False
Me.txtProduto.Locked = False
Me.txtEmail.Locked = False
Me.txtValorCotado.Locked = False
Me.txtRegiao.Locked = False
Me.txtOutrosProdutos.Locked = False
Me.txtSkype.Locked = False
Me.txtHomePage.Locked = False
Me.txtNomeEmpresa.BackColor = corEnabledTextBox
Me.txtCNPJ.BackColor = corEnabledTextBox
Me.txtFone.BackColor = corEnabledTextBox
Me.txtContato.BackColor = corEnabledTextBox
Me.txtProduto.BackColor = corEnabledTextBox
Me.txtEmail.BackColor = corEnabledTextBox
Me.txtValorCotado.BackColor = corEnabledTextBox
Me.txtRegiao.BackColor = corEnabledTextBox
Me.txtOutrosProdutos.BackColor = corEnabledTextBox
Me.txtSkype.BackColor = corEnabledTextBox
Me.txtHomePage.BackColor = corEnabledTextBox
End Sub
Private Sub DesabilitaControles()
'Me.txtCodigoFornecedor.Locked = True
Me.txtNomeEmpresa.Locked = True
Me.txtCNPJ.Locked = True
Me.txtFone.Locked = True
Me.txtContato.Locked = True
Me.txtProduto.Locked = True
Me.txtEmail.Locked = True
Me.txtValorCotado.Locked = True
Me.txtRegiao.Locked = True
Me.txtOutrosProdutos.Locked = True
Me.txtSkype.Locked = True
Me.txtHomePage.Locked = True
Me.txtNomeEmpresa.BackColor = corDisabledTextBox
Me.txtCNPJ.BackColor = corDisabledTextBox
Me.txtFone.BackColor = corDisabledTextBox
Me.txtContato.BackColor = corDisabledTextBox
Me.txtProduto.BackColor = corDisabledTextBox
Me.txtEmail.BackColor = corDisabledTextBox
Me.txtValorCotado.BackColor = corDisabledTextBox
Me.txtRegiao.BackColor = corDisabledTextBox
Me.txtOutrosProdutos.BackColor = corDisabledTextBox
Me.txtSkype.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
Private Sub DefinePlanilhaDados()
Dim abrirArquivo As Boolean
Dim wb As Workbook
Dim caminhoCompleto As String
Dim ARQUIVO_DADOS As String
Dim PASTA_DADOS As String
abrirArquivo = True
ARQUIVO_DADOS = Range("ARQUIVO_DADOS").Value
PASTA_DADOS = Range("PASTA_DADOS").Value
If ThisWorkbook.Name <> ARQUIVO_DADOS Then
'monta a string do caminho completo
If PASTA_DADOS = vbNullString Or PASTA_DADOS = "" Then
caminhoCompleto = Replace(ThisWorkbook.FullName, ThisWorkbook.Name, vbNullString) & ARQUIVO_DADOS
Else
If Right(PASTA_DADOS, 1) = "\" Then
caminhoCompleto = PASTA_DADOS & ARQUIVO_DADOS
Else
caminhoCompleto = PASTA_DADOS & "\" & ARQUIVO_DADOS
End If
End If
'verifica se o arquivo não está aberto
For Each wb In Application.Workbooks
If wb.Name = ARQUIVO_DADOS Then
abrirArquivo = False
Exit For
End If
Next
'atribui o arquivo
If abrirArquivo Then
Set wbCadastro = Workbooks.Open(Filename:=caminhoCompleto, ReadOnly:=True)
Else
Set wbCadastro = Workbooks(ARQUIVO_DADOS)
End If
Else
Set wbCadastro = ThisWorkbook
End If
Set wsCadastro = wbCadastro.Worksheets(nomePlanilhaCadastro)
'oculta o arquivo de dados
wbCadastro.Windows(1).Visible = False
End Sub
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
-------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------
Isso é o que está no formulário de pesquisa, o fmPesquisa:
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
'Adaptação Mauro Coutinho com LISTVIEW
'Julho de 2011
Option Explicit
'constantes para auxiliar na verificação do código
Private Const Ascendente As Byte = 0
Private Const Descendente As Byte = 1
Private caminhoArquivoDados As String
'INICIO - REDIMENSIONAR AUTOMATICAMENTE COLUNAS DO LISTVIEW
'TamanhoColAutomatico - 'Define os Tamanhos das colunas automaticamente
'
http://www.vb6.com.br/29/Controles-Micr ... TVIEW.html
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Const LVM_FIRST = &H1000
Private Const LVM_SETCOLUMNWIDTH = (LVM_FIRST + 30)
Private Const LVSCW_AUTOSIZE = -1
Private Const LVSCW_AUTOSIZE_USEHEADER = -2
'FIM - REDIMENSIONAR AUTOMATICAMENTE COLUNAS DO LISTVIEW
Private Sub btnExportar_Click()
Call Exportar
End Sub
Private Sub btnFiltrar_Click()
Call PopulaListBox(txtNomeEmpresa.Text, txtFone.Text, txtContato.Text, txtOutrosProdutos.Text, txtEmail.Text)
End Sub
Private Sub frmFiltros_Click()
End Sub
Private Sub lblContato_Click()
End Sub
Private Sub lblProduto_Click()
End Sub
Private Sub lblFone_Click()
End Sub
Private Sub lblOutrosProdutos_Click()
End Sub
Private Sub lblEmail_Click()
End Sub
Private Sub lstProduto_Click()
End Sub
Private Sub lstLista_DblClick()
Dim linha, Index
Dim i As Integer
Dim oList As Object
Dim indiceRegistro As Long
On Error Resume Next
Set oList = lstLista.SelectedItem
If oList Is Nothing Then 'Exit Sub
lblMensagens.Caption = "É preciso selecionar um item válido na lista"
Else
indiceRegistro = frmCadastro.ProcuraIndiceRegistroPodId(lstLista.ListItems.Item(lstLista.SelectedItem.Index))
If indiceRegistro <> -1 Then
Call frmCadastro.CarregaRegistroPorIndice(indiceRegistro)
End If
Unload Me
End If
End Sub
Private Sub DefinePlanilhaDados()
Dim wb As Workbook
Dim caminhoCompleto As String
Dim ARQUIVO_DADOS As String
Dim PASTA_DADOS As String
ThisWorkbook.Activate
ARQUIVO_DADOS = Range("ARQUIVO_DADOS").Value
PASTA_DADOS = Range("PASTA_DADOS").Value
If ThisWorkbook.Name <> ARQUIVO_DADOS Then
'monta a string do caminho completo
If PASTA_DADOS = vbNullString Or PASTA_DADOS = "" Then
caminhoCompleto = Replace(ThisWorkbook.FullName, ThisWorkbook.Name, vbNullString) & ARQUIVO_DADOS
Else
If Right(PASTA_DADOS, 1) = "\" Then
caminhoCompleto = PASTA_DADOS & ARQUIVO_DADOS
Else
caminhoCompleto = PASTA_DADOS & "\" & ARQUIVO_DADOS
End If
End If
End If
caminhoArquivoDados = caminhoCompleto
End Sub
Private Sub txtContato_Change()
End Sub
Private Sub txtFone_Change()
End Sub
Private Sub txtProduto_Change()
End Sub
Private Sub txtNomeEmpresa_Change()
End Sub
Private Sub txtOutrosProdutos_Change()
End Sub
Private Sub txtEmail_Change()
End Sub
Private Sub UserForm_Initialize()
'lv.ListItems.Clear 'Clear ListView from previous filled data
lstLista.ColumnHeaders.Clear 'Clear the Column Headers
lstLista.ListItems.Clear
With lstLista
.Gridlines = True
.View = lvwReport
'.FullRowSelect
' .ColumnHeaders.Add Text:="ID", Width:=20
' .ColumnHeaders.Add Text:="Nome", Width:=60
' .ColumnHeaders.Add Text:="Contato", Width:=120
' .ColumnHeaders.Add Text:="Fone", Width:=30
' .ColumnHeaders.Add Text:="Produtos", Width:=50
End With
'preenche o cboDirecao e seleciona o primeiro item
cboDirecao.Clear
cboDirecao.AddItem "Ascendente"
cboDirecao.AddItem "Descendente"
cboDirecao.ListIndex = 0
Call DefinePlanilhaDados
Call PopulaProduto
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, txtFone.Text, txtContato.Text, txtOutrosProdutos.Text, txtEmail.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 PopulaProduto()
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=" & caminhoArquivoDados & ";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
lstProduto.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 Fone As String, _
ByVal Contato As String, _
ByVal OutrosProdutos As String, _
ByVal Email As String)
On Error GoTo TrataErro
Dim rst As ADODB.Recordset
Dim campo As Field
Dim myArray() As Variant
Dim i As Integer
Dim li As ListItem, fld As Field, ch As ColumnHeader
Dim Column As Long
Dim Counter As Long
Counter = 0
Set rst = PreecheRecordSet(NomeEmpresa, Fone, Contato, OutrosProdutos, Email)
'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
'Colunas a Preencher Inicia na Primeira
For i = 0 To rst.Fields.Count - 1 'For i = 1 : a partir da 2ª coluna
Set ch = lstLista.ColumnHeaders.Add(, , rst.Fields(i).Name)
'ch.Width = 48 'Define o Tamanho de Todas as COLUNAS
'MsgBox rst.Fields(i).Name
Next
'Clear the Column Headers
lstLista.ListItems.Clear
'coloca as linhas do RecordSet num Array, se houver linhas neste
If Not rst.BOF Then
Do While Not rst.EOF
'Preenche o LISTVIEW a partir da 2ª Coluna
'Set li = lstLista.ListItems.Add(, "k" & rst.Fields(0), CheckNull(rst.Fields(1)))
'Fill in the rest of the columns
'For i = 2 To rst.Fields.Count - 1
'li.SubItems(i - 1) = CheckNull(rst.Fields(i))
'Preenche o LISTVIEW a partir da 1ª Coluna
Set li = lstLista.ListItems.Add(, "k" & rst.Fields(0), CheckNull(rst.Fields(0)))
'Fill in the rest of the columns
For i = 1 To rst.Fields.Count - 1
li.SubItems(i) = CheckNull(rst.Fields(i))
Next
rst.MoveNext 'Move to next record
Loop
'Define os Tamanhos das colunas automaticamente
Call TamanhoColAutomatico
End If
'atualiza o label de mensagens
If rst.RecordCount <= 0 Then
lblMensagens.Caption = rst.RecordCount & " registros encontrados"
Else
lblMensagens.Caption = rst.RecordCount & " registros encontrados"
End If
Exit Sub
' 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
MsgBox Err.Description & vbNewLine & Err.Number & vbNewLine & Err.Source
Resume TrataSaida
End Sub
Private Sub TamanhoColAutomatico()
Dim Column As Long
Dim Counter As Long
Counter = 0
For Column = Counter To lstLista.ColumnHeaders.Count - 2
SendMessage lstLista.hWnd, LVM_SETCOLUMNWIDTH, Column, LVSCW_AUTOSIZE_USEHEADER
Next
End Sub
Public Function CheckNull(FieldValue As Variant)
On Error GoTo Error
If IsNull(FieldValue) Then
CheckNull = ""
Else
CheckNull = FieldValue
End If
' Exit Sub
Error:
'GeneralErrors "CheckNull", Err.Number, Err.Description
Resume Next
End Function
Private Function PreecheRecordSet(ByVal NomeEmpresa As String, _
ByVal Fone As String, _
ByVal Contato As String, _
ByVal OutrosProdutos As String, _
ByVal Email 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=" & caminhoArquivoDados & ";Extended Properties=Excel 8.0;"
.Open
End With
sql = "SELECT * FROM [Fornecedores$]"
'monta a cláusula WHERE
'NomeDaEmpresa
Call MontaClausulaWhere(txtNomeEmpresa.Name, "NomeDaEmpresa", sqlWhere)
'Fone
Call MontaClausulaWhere(txtFone.Name, "Fone", sqlWhere)
'Contato
Call MontaClausulaWhere(txtContato.Name, "Contato", sqlWhere)
'Produto
For i = 1 To lstProduto.ListCount
'verifica se o item está selecionado
If lstProduto.Selected(i - 1) Then
'Monta a cláusula WHERE com OR
Debug.Print lstProduto.List(i - 1) & " selecionado"
If sqlWhere <> vbNullString Then
sqlWhere = sqlWhere & " OR"
End If
sqlWhere = sqlWhere & " UCASE(Cidade) LIKE UCASE('%" & Trim(lstProduto.List(i - 1)) & "%')"
End If
Next
'OutrosProdutos
Call MontaClausulaWhere(txtOutrosProdutos.Name, "OutrosProdutos", sqlWhere)
'Região
Call MontaClausulaWhere(txtEmail.Name, "Email", 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)
'Fone
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
Acredito que agora ficará mais fácil, grato dês de já pela atenção de todos.
Abraço