Advertisement
wanderleihuttel

Importar arquivo VBA

Nov 1st, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. '################################################################################################################
  2. ' Esta função serve para abrir o OpenDialogFile
  3. '
  4. ' @author  Wanderlei Hüttel <wanderlei dot huttel at gmail dot com>
  5. ' @name    fnAbrirArquivo
  6. ' @param   'string'      strFileName      Nome do arquivo/diretório inicial
  7. ' @param   'integer'     iPath            Caminho padrão inicial
  8. ' @return  'string'                       String com o caminho do arquivo
  9. Public Function fnAbrirArquivo(sFileName As String, Optional ByVal iPath As Integer = 0) As String
  10.    Dim fd As Office.FileDialog
  11.    Dim vrtSelectedItem As Variant
  12.    Set fd = Application.FileDialog(msoFileDialogFilePicker)
  13.    
  14.     ' Define o caminho padrão para salvar o arquivo'
  15.    ' Desktop do usuário
  16.    If (iPath = 1) Then
  17.        sPath = Environ$("USERPROFILE") & "\Desktop\" & sFileName
  18.     ' Caminho especifico
  19.    ElseIf (iPath = 2) Then
  20.        sPath = sFileName
  21.     ' Raiz da planilha
  22.    Else
  23.        sPath = ActiveWorkbook.Path & "\" & sFileName
  24.     End If
  25.    
  26.     With fd
  27.         .AllowMultiSelect = False
  28.         .Filters.Add "Todos os Arquivos", "*.*", 1
  29.         .Filters.Add "Arquivos Texto", "*.csv", 1
  30.         .Filters.Add "Arquivos Texto", "*.txt", 1
  31.         .InitialFileName = sPath
  32.        
  33.         If .Show = -1 Then
  34.             For Each vrtSelectedItem In .SelectedItems
  35.                 sPath = vrtSelectedItem 'Caminho e nome do arquivo
  36.                fnAbrirArquivo = CStr(sPath)
  37.                 Next vrtSelectedItem
  38.         Else
  39.            fnAbrirArquivo = ""
  40.         End If
  41.     End With
  42.     Set fd = Nothing
  43. End Function
  44.  
  45. '################################################################################################################
  46. ' Esta função serve para remover múltiplos espaços de String
  47. '
  48. ' @author  Wanderlei Hüttel <wanderlei dot huttel at gmail dot com>
  49. ' @name    fnDeleteMultipleSpaces
  50. ' @param   'string'      sString          String com espaços
  51. ' @return  'string'                       String sem múltiplos espaços
  52. Public Function fnDeleteMultipleSpaces(sString As String) As String
  53.   sString = Replace(sString, vbTab, " ")
  54.   Do While InStr(sString, "  ") > 0
  55.     sString = Replace(sString, "  ", " ")
  56.   Loop
  57.   fnDeleteMultipleSpaces = sString
  58. End Function
  59.  
  60. '########## Função Importar Arquivo ##########
  61. Public Sub ImportarArquivo()
  62.    Dim linha As String
  63.  
  64.    Temp.Range("A1:IV65536").ClearContents
  65.    Temp.Range("A1:IV65536").Font.Name = "Courier New"
  66.    Temp.Range("A1:IV65536").Font.Size = 8
  67.    
  68.     'Caixa de seleção de arquivo
  69.    arquivo = fnAbrirArquivo("")
  70.    
  71.     ' Se arquivo for vazio para a macro
  72.    If arquivo = "" Then
  73.        Exit Sub
  74.     End If
  75.    
  76.     ' Abre o arquivo a ser importado
  77.    Open arquivo For Input As #1
  78.    
  79.      ' Looping pelas linhas do arquivo
  80.     i = 2
  81.      j = 0
  82.      
  83.      Temp.Range("G:I").NumberFormat = "#,##0.00"
  84.      Temp.Range("E:F").NumberFormat = "@"
  85.      Do While Not EOF(1)
  86.         Line Input #1, linha
  87.        
  88.         ' Remove múltiplos espaços e substitui TAB por espaço
  89.        linha = Trim(fnDeleteMultipleSpaces(linha))
  90.        
  91.         If (j = 3017) Then
  92.             x = 1
  93.         End If
  94.        
  95.         ' Remove o campo Valor Total do Cliente
  96.        If (InStr(1, linha, "Vl. Total do Cliente", 1)) Then
  97.            Line Input #1, linha
  98.            linha = Trim(fnDeleteMultipleSpaces(linha))
  99.            i = i - 1
  100.            Temp.Cells(i, 1) = ""
  101.         End If
  102.        
  103.         ' Remove o campo Valor Total
  104.        If InStr(1, linha, "Vl. Total ", 1) Then
  105.            Line Input #1, linha
  106.            linha = Trim(fnDeleteMultipleSpaces(linha))
  107.            i = i - 1
  108.            Temp.Cells(i, 1) = ""
  109.         End If
  110.        
  111.         'Pega o código e nome do cliente
  112.        If InStr(1, linha, "Cliente :", 1) Then
  113.           cliente = Trim(Replace(linha, "Cliente :", ""))
  114.           cliente_aux = Split(cliente, "-")
  115.           codigo_cliente = Trim(cliente_aux(0))
  116.           nome_cliente = Trim(cliente_aux(1))
  117.           Line Input #1, linha
  118.           linha = Trim(fnDeleteMultipleSpaces(linha))
  119.         End If
  120.        
  121.        
  122.         'Se a linha não for vazia
  123.        If (Len(Trim((linha))) > 0 And j > 8) Then
  124.            
  125.             If (Len(Trim((linha))) > 40) Then
  126.                 reg = Split(linha, " ")
  127.                 filial = reg(0)
  128.                 lancamento = Replace(reg(1), ".", "")
  129.                 documento = reg(2)
  130.                 parcela_aux = Split(reg(3), "/")
  131.                 parcela = parcela_aux(1)
  132.                 data_emissao = reg(4)
  133.                 data_vencimento = reg(5)
  134.                 valor_parcela = reg(6)
  135.                 valor_recebido = reg(7)
  136.                 valor_saldo = reg(8)
  137.                
  138.                 Temp.Cells(i, 1) = filial
  139.                 Temp.Cells(i, 2) = lancamento
  140.                 Temp.Cells(i, 3) = documento
  141.                 Temp.Cells(i, 4) = parcela
  142.                 Temp.Cells(i, 5) = data_emissao
  143.                 Temp.Cells(i, 6) = data_vencimento
  144.                 Temp.Cells(i, 7) = CDbl(valor_parcela)
  145.                 Temp.Cells(i, 8) = CDbl(valor_recebido)
  146.                 Temp.Cells(i, 9) = CDbl(valor_saldo)
  147.                 Temp.Cells(i, 10) = codigo_cliente
  148.                 Temp.Cells(i, 11) = nome_cliente
  149.             End If
  150.            
  151.            i = i + 1
  152.         End If
  153.         j = j + 1
  154.      Loop
  155.      
  156.     ' Fecha o arquivo
  157.    Close #1
  158.    
  159.     Range("A1").Select
  160.     retorno = MsgBox("Arquivo Importado Com Sucesso !!!", vbInformation)
  161.    
  162. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement