Dúvida modelo de aplicativo form de pesquisa

Lidia

30-01-2011 22:15:16

mas um problema.... Deus mande alguém pra me ajudarO form de cadastro ta tudo certo agora é o de pesquisa mudei os campos e tirei alguns.
O form abre mas não filtra nem preenche o combo muito menos exporta.
Também um erro quando tento exporta:
Erro de Compilação
Número de argumentos incorretos ou atribuição de propriedade inválida
Na linha
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(txtNome.Text,

E gostaria de exporta para uma planilha na mesma pasta da forma que esta no modelo ele cria uma nova pasta.
Meu formulário tem esses campo txtNome, txtIso, txtfornecedor, txtAreaRamal, txtMatricula, cboordenarpor e Exporta e filtrar

O código completo
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 PopulalstLista(txtNome.Text, txtIso.Text, txtFornecedor.Text, txtAreaRamal.Text, txtMatricula.Text)
End Sub

Private Sub cboDirecao_Change()

End Sub

Private Sub cboOrdenarPor_Change()

End Sub

Private Sub frmFiltros_Click()

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(txtNome.Text, txtIso.Text, txtFornecedor.Text, txtAreaRamal.Text, txtMatricula.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 PopulaMatricula()
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 Matricula FROM [Auditores]"

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
lstMatricula.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 PopulacboOrdenarPor(ByVal Nome As String, _
ByVal Iso As String, _
ByVal Fornecedor As String, _
ByVal AreaRamal 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(Nome, Iso, Fornecedor, AreaRamal)

'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 Nome As String, _
ByVal Iso As String, _
ByVal Fornecedor As String, _
ByVal AreaRamal 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 [Relatório]"

'monta a cláusula WHERE
'Nome
Call MontaClausulaWhere(txtNome.Name, "Nome", sqlWhere)

'iso
Call MontaClausulaWhere(txtIso.Name, "ISO", sqlWhere)

'Fornecedor
Call MontaClausulaWhere(txtFornecedor.Name, "Fornecedor", sqlWhere)

'Matricula
'For i = 1 To lstMatricula.ListCount
'verifica se o item está selecionado
'If lstMatricula.Selected(i - 1) Then
'Monta a cláusula WHERE com OR
'Debug.Print lstMatricula.List(i - 1) & " selecionado"
'If sqlWhere <> vbNullString Then
'sqlWhere = sqlWhere & " OR"
'End If
'sqlWhere = sqlWhere & " UCASE(Matricula) LIKE UCASE('%" & Trim(lstMatricula.List(i - 1)) & "%')"
'End If
' Next

'arearamal
Call MontaClausulaWhere(txtAreaRamal.Name, "Área/Ramal", sqlWhere)

'matricula
Call MontaClausulaWhere(txtMatricula.Name, "Matrícula", 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)
'Iso
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 lstLista_Click()

End Sub

Private Sub txtMatricula_Change()

End Sub

Private Sub txtNome_Change()

End Sub

Mauro Coutinho

30-01-2011 23:51:24

Lidia, acredito que no céu não tenha computador e não precisa ir tão longe a ponto de pedir ajuda ao Divino, não sou muito do tipo religioso, mas acredito ser uma eresia chamar o nome do SENHOR em vão, aqui no forum temos alguns colaboradores que podemos chamar de "deuses do VBA" e que ajudarão sem que seja preciso muita oração.

Voltando a sua solicitação, vou reforçar o que eu disse na ajuda anterior sobre o Form CADASTRO, para você ler com atenção todos osTópicos que se referem ao Modelo cadastro V3 no Forum TUTORIAIS e DICAS a começar por este :
Modelo Cadastro V3 - Adaptações
viewtopic.php?f=16&t=595

Neste Modelo criado pelo grande Tomas é imprensindivel ter um pouco de afinidade com VBA e prestar bastante atenção quanto às mudanças de Nomes dos Controles e Constantes e Argumentos, e fica um praticamente impossível achar aonde está o erro se não temos o Modelo que você está Adaptadando.
Po exemplo, você tem um controle como o Nome txtMatricula e ele deve estar ligado a uma constante ou variável na Rotina e mais um Indice em sua Planilha, então se não visualizarmos não poderemos saber como referencia-la corretamente.

Se for possivel anexe seu Modelo.

[]s

Perola

19-04-2011 16:59:27

Boa tarde,

peço desculpa se não estou a colocar a duvida no lugar correcto... mas sou iniciante... estou adaptando o modelo de cadastro v2 e tenho um problema no form pesquisa pois gostaria que a listbox iniciasse na linha 19 e não na linha 2. Vou necessitar dessas 19 linhas somente para preenchimento de um campo e gostaria que elas estivessem ocultas e não aparecessem quando abrimos o form pesquisa.

Obrigado pela ajudas.