Formatando valores Texto do Listview para Numerico(resolvido

Rodrigo

27-11-2010 01:27:25

Fala Mauro,

Matou a pau, muito obrigado. Mas isso resolveu 90% dos problemas. Ainda tem um problema no banco de dados.

Na função Private Sub SalvaRegistro4 que foi criada por você ele pega as informações que estão no lisview e joga para o banco de dados, o problema é que ele está jogando como texto ainda

Isso está acontecendo pq no comando Preencher lista view ele formata com0 R$, tentei usar CCur mas ele não formatou

Tentei uma outra opção que é CCur(ListView1.ListItems(i).ListSubItems(j).Text) que tiraria a formatação na hora de jogar no banco de dados. Deu erro pois no listview tbm há texto, ou seja, quando chega na hora de formatar o texto dá erro.

Você acha que existe alguma solução ?

Preenche o lisview e formatar as coluna que tem valores com R$

Código: Selecionar todos

Sub PreencherListView()
On Error GoTo Erro
Dim lastRow As Long
Dim li As ListItem
Dim x As Long
Dim wsCadastro2 As Long
Workbooks("Caixa.xls").Worksheets("Calculo").Visible = True
    ' Adiciona as colunas
   With ListView1
        .Gridlines = True
        .View = lvwReport
        '.FullRowSelect
        .ColumnHeaders.Add Text:="ID", Width:=10
        .ColumnHeaders.Add Text:="PRODUTO", Width:=80
        .ColumnHeaders.Add Text:="DESCRIÇÃO DO PRODUTO", Width:=120
        .ColumnHeaders.Add Text:="TIPO", Width:=20
        .ColumnHeaders.Add Text:="QTDE", Width:=40
        .ColumnHeaders.Add Text:="PREÇO UN", Width:=60
        .ColumnHeaders.Add Text:="P_TOTAL", Width:=50
        .ColumnHeaders.Add Text:="LINHA DE NEGOCIO", Width:=60
        .ColumnHeaders.Add Text:="LINHA DE PRODUTO", Width:=30
        .ColumnHeaders.Add Text:="Custo_total_produto", Width:=60
    End With
    '...................................................................
'limpar
ListView1.ListItems.Clear
    lastRow = Sheet1.Cells(Sheet1.Cells.Rows.Count, "a").End(xlUp).Row
    ' Adiciona itens
   For x = 2 To lastRow
        Set li = ListView1.ListItems.Add(Text:=Sheet1.Cells(x, "a").Value)
        li.ListSubItems.Add Text:=Sheet1.Cells(x, "b").Value
        li.ListSubItems.Add Text:=Sheet1.Cells(x, "c").Value
        li.ListSubItems.Add Text:=Sheet1.Cells(x, "d").Value
        li.ListSubItems.Add Text:=Sheet1.Cells(x, "E").Value
        li.ListSubItems.Add Text:=Format(Sheet1.Cells(x, "F").Value, "currency")
        li.ListSubItems.Add Text:=Format(Sheet1.Cells(x, "G").Value, "currency")
        li.ListSubItems.Add Text:=Sheet1.Cells(x, "H").Value
        li.ListSubItems.Add Text:=Sheet1.Cells(x, "I").Value
        li.ListSubItems.Add Text:=Format(Sheet1.Cells(x, "J").Value, "currency")
    Next
'Somar lisview
    Dim i As Long
    Dim valor As Double
    For i = 1 To Me.ListView1.ListItems.Count
        valor = valor + CDbl(Me.ListView1.ListItems(i).ListSubItems(6))
    Next i
   Label66.Caption = valor
   Label66.Caption = Format(Label66.Caption, "currency")
   Call QTDE
   Workbooks("Caixa.xls").Worksheets("Calculo").Visible = False
Erro:
End Sub
O código abaixo copia os dados do lisviw e joga no bando de dados

Código: Selecionar todos

Private Sub SalvaRegistro4(ByVal id As Long, ByVal indice2 As Long)
   Dim i As Integer, j As Integer
    'tenta abrir o arquivo em modo escrita
    Call AtualizarArquivo4(False)
    'Criar um loop onde campo txtnomeempresa e txtnomecontato deve se repitir para cada linha do listview
    With wsCadastro4
        'Loop as lignes
        For i = 1 To ListView1.ListItems.Count
            .Cells(indice2, 2) = ListView1.ListItems(i).Text
            .Cells(indice2, colCodigoDoFornecedor).Value = id
            'Loop as colunas
                For j = 1 To ListView1.ColumnHeaders.Count - 1
                    .Cells(indice2, j + 2) = ListView1.ListItems(i).ListSubItems(j).Text
                    .Cells(indice2, colusuario).Value = Label51.Caption
                    .Cells(indice2, coldata).Value = Label53.Caption
                    .Cells(indice2, colmes).Value = Label82.Caption
                    .Cells(indice2, colsemana).Value = Label58.Caption
                    .Cells(indice2, colano).Value = Label83.Caption
                    .Cells(indice2, colNF).Value = Label77.Caption
                    .Cells(indice2, ColFpgto).Value = ComboBox1.Text
                    .Cells(indice2, colhora).Value = Time()
                    .Cells(indice2, colhorariopico).Value = Label98.Caption
                Next j
            indice2 = indice2 + 1
            id = id + 1
        Next i
    End With
    'salva o arquivo
    Call wbCadastro4.Save
    'abre o arquivo novamente em modo leitura
    Call AtualizarArquivo4(True)
    Call LipezaGeral
    Call PreencherListView
End Sub

Rodrigo

28-11-2010 20:26:58

Fala Obrigado, sem problemas.

Vc acha que essa questão é complexo ? só falta isso para eu terminar meu projeto.

Estou totalmente disesperado, não sei o que fazer.

Aguardo sua resposta

Mauro Coutinho

29-11-2010 02:27:22

Rodrigo, na Rotina PreencherListView você alimenta o Listview com esta formatação (Currency) em 3 colunas, e não identifiquei na rotina SalvaRegistro4 aonde os mesmos são descarregados, então vou colocar somente uma parte da adaptação que fiz em uma Rotina de um dos exemplos que tinha anexado em tópicos anteriores, depois acerte na rotina que está usando.

Como diz que no Listview o valor é formatado com R$, fiz o seguinte, quando do Loop nos registros do Listview usei a condição IF para verificar a existencia deste Sinal - R$, e se Verdadeiro converte o mesmo para numerico e depois devolve para a planilha formatado usando a Função de Conversão CCur como Numerico.

Código: Selecionar todos

     Private Sub SalvaRegistro4(ByVal id As Long, ByVal indice2 As Long)
       Dim I As Integer, j As Integer
       Dim sSinal
        'tenta abrir o arquivo em modo escrita
        Call AtualizarArquivo(False)
         
        'Criar um loop onde campo txtnomeempresa e txtnomecontato deve se repitir para cada linha do listview
        With wsBD_Faturam
           
            'Loop as lignes
            For I = 1 To ListView1.ListItems.Count
                .Cells(indice2, 2) = ListView1.ListItems(I).Text
                .Cells(indice2, colCodigoDoFornecedor).Value = id
                'Loop as colunas
                    For j = 1 To ListView1.ColumnHeaders.Count - 1
                        
                        .Cells(indice2, j + 2) = ListView1.ListItems(I).ListSubItems(j).Text

'AQUI É FEITO A VERFICIAÇÃO DA  EXISTENCIA DO SINAL
    If Left(ListView1.ListItems(I).ListSubItems(j).Text, 2) = "R$" Then
'..........'SE POSITIVO CONVERTE O VALOR TEXTO PARA NUMÉRICO
            sSinal = CLng(ListView1.ListItems(I).ListSubItems(j).Text)
'.......DEPOIS DEVOLVE PARA A PLANILHA COMO NUMERICO E FORMATADO
        .Cells(indice2, j + 2) = CCur(sSinal)
    End If
                        
                        .Cells(indice2, colusuario).Value = TextBox1.Value
                        .Cells(indice2, ColFpgto).Value = ComboBox1.Text
                        .Cells(indice2, colhora).Value = Time()
                       
                    Next j
                indice2 = indice2 + 1
                id = id + 1
            Next I

        End With
       
        'salva o arquivo
        Call wbCadastro4.Save
       
        'abre o arquivo novamente em modo leitura
        Call AtualizarArquivo(True)
     
    End Sub
Faça os teste e veja se é isto.

abraços

Rodrigo

30-11-2010 02:16:34

Fala Mauro,

Cara, sem palavras...você realmente matou a pau !!!

Muito obrigado pela sua ajuda... agora vou conseguir durmir em paz..rsrrss :D

Um forte abraço !!