IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Macros et VBA Excel Discussion :

Importer ou transformer automatiquement un fichier .txt en excel, est -il possible ?


Sujet :

Macros et VBA Excel

  1. #1
    Membre régulier
    Profil pro
    Inscrit en
    Janvier 2008
    Messages
    460
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2008
    Messages : 460
    Points : 71
    Points
    71
    Par défaut Importer ou transformer automatiquement un fichier .txt en excel, est -il possible ?
    Bonjour,

    Comment Importer ou transformer un fichier .txt en excel automatiquement en VBA, est -il possible ? pour gagner du tps... car un peu galère manuellement.

    Mon pb : je fais des extractions tout les jours d 'une appli intranet et j'ai besoin d 'automatiser pour transformer un fichier .txt en excel automatiquement.

    comment faire ? en vba pour que les données du fichier texte soient bien poisitionnées dans un format excel.

    Merci pour votre aide

  2. #2
    Expert éminent sénior
    Homme Profil pro
    aucune
    Inscrit en
    Septembre 2011
    Messages
    8 203
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Septembre 2011
    Messages : 8 203
    Points : 14 354
    Points
    14 354
    Par défaut
    Bonjour,

    Active l'enregistreur de macros et fais la manip manuellement (et arrête l'enregistreur).
    Cordialement.

    Daniel

    La plus perdue de toutes les journées est celle où l'on n'a pas ri. Chamfort

  3. #3
    Membre régulier
    Profil pro
    Inscrit en
    Janvier 2008
    Messages
    460
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2008
    Messages : 460
    Points : 71
    Points
    71
    Par défaut
    J'ai plusieurs fois la manip à faire par jou je voudrais une fois les données en .txt exporter les sauvegarder dans un fichier tampon puis avec une macro dédiée transformer le fichier .txt en fichier excel.

    Merci mais pas très pratique (est-ce du bricolage ? ) , y-a-t-il une possibilité par vba simple ?

  4. #4
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    Salut,ceci n'est qu'un exemple perfectible sans doute et à adapter surement pour LectureTXT

    Dans un modulestandard baptisé par exemple mImport
    Affecter un bouton à SelFichier
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
     
    Option Explicit
     
    Public sNomFichierImport As String
     
    Sub SelFichier()
    Dim sChemin As String
        sChemin = ThisWorkbook.Path
     
        With Application.FileDialog(msoFileDialogFilePicker)
            .InitialFileName = sChemin & "\"
            .Title = "Sélectionner le fichier TXT"
            .AllowMultiSelect = False
            .ButtonName = "Sélection Fichier"
     
            .Filters.Clear
            .Filters.Add "Texte", "*.txt"
     
            .Show
            If .SelectedItems.Count > 0 Then
                DoEvents
                Application.ScreenUpdating = False
                ShDatas.Cells.Clear
     
                sNomFichierImport = .SelectedItems(1)
     
                LectureTXT .SelectedItems(1)
     
                With ShDatas
                    .Activate
                    .Range("A1").Select
                End With
                Application.ScreenUpdating = True
            End If
        End With
    End Sub
     
    Private Sub LectureTXT(sFichier As String)
    Dim iRow As Long, iCol As Long
    Dim NumFichier As Integer
    Dim sChaine As String, i As Long
    Dim Separateur As String, Ar() As String
     
        NumFichier = FreeFile
        Separateur = vbTab
     
        iRow = 1
        Open sFichier For Input As NumFichier
            Do While Not EOF(NumFichier)
                iCol = 1
                Line Input #NumFichier, sChaine
                Ar = Split(sChaine, Separateur)
                For i = LBound(Ar) To UBound(Ar)
                    If IsDate(Ar(i)) Then
                        ShDatas.Cells(iRow, iCol) = CDate(Ar(i))
                    Else
                        ShDatas.Cells(iRow, iCol) = Ar(i)
                    End If
                    iCol = iCol + 1
                Next i
                iRow = iRow + 1
            Loop
        Close NumFichier
    End Sub
    Dans un autre module standard baptisé par exemple mSauvegarde
    Affecter un bouton à Sauvegarde
    ShDatas est le CodeName de la feuille recevant les données du fichier texte
    voir http://www.developpez.net/forums/d92...cel/vba-bases/
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
     
    Option Explicit
     
    Sub Sauvegarde()
    Dim WkbDep As Workbook
    Dim WkbSave As Workbook
    Dim sNomXLS As String
    Dim Rep As Long
     
        If Len(sNomFichierImport) = 0 Then Exit Sub
        sNomXLS = Left$(sNomFichierImport, InStrRev(sNomFichierImport, ".") - 1) & ".xls"
     
        If ExistenceFichier(sNomXLS) Then
            Rep = MsgBox("Ce fichier existe déjà" & vbCrLf & vbCrLf & "Voulez-vous l'écraser ?", vbCritical + vbYesNo, "Ecraser le fichier")
            Select Case Rep
                Case 6
                    Application.ScreenUpdating = False
     
                    Set WkbDep = ThisWorkbook
                    WkbDep.Sheets(ShDatas.Name).UsedRange.Copy
     
                    Set WkbSave = Workbooks.Add
                    With ActiveSheet
                        .Paste
                        .Range("A1").Select
                    End With
     
                    With Application
                        .CutCopyMode = False
                        .DisplayAlerts = False
                    End With
     
                    WkbSave.SaveAs Filename:=sNomXLS, FileFormat:=xlNormal
                    ActiveWindow.Close
     
                    With Application
                        .DisplayAlerts = True
                        .ScreenUpdating = True
                    End With
     
                    Set WkbDep = Nothing
                    Set WkbSave = Nothing
            End Select
        Else
            Application.ScreenUpdating = False
     
            Set WkbDep = ThisWorkbook
            WkbDep.Sheets(ShDatas.Name).UsedRange.Copy
     
            Set WkbSave = Workbooks.Add
            With ActiveSheet
                .Paste
                .Range("A1").Select
            End With
     
            Application.CutCopyMode = False
     
            WkbSave.SaveAs Filename:=sNomXLS, FileFormat:=xlNormal
            ActiveWindow.Close
            Application.ScreenUpdating = True
     
            Set WkbDep = Nothing
            Set WkbSave = Nothing
        End If
    End Sub
     
    Private Function ExistenceFichier(sFichier As String) As Boolean
        ExistenceFichier = Dir$(sFichier) <> ""
    End Function
    L'ensemble est concaténable très facilement dans un seul module si l'on ne veut pas 2 étapes Import et Sauvegarde

  5. #5
    Membre régulier
    Profil pro
    Inscrit en
    Janvier 2008
    Messages
    460
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2008
    Messages : 460
    Points : 71
    Points
    71
    Par défaut
    Merci pour votre mais j'ai placé les deux codes mais n'arrive pas à le faire fonctionner, pouvez vous jeter un oeil ?

    L'idée est simple transférer un fichier texte dans excel.

    est ce que le placement du code est bon ?

  6. #6
    Membre chevronné
    Inscrit en
    Août 2006
    Messages
    1 588
    Détails du profil
    Informations forums :
    Inscription : Août 2006
    Messages : 1 588
    Points : 2 178
    Points
    2 178
    Par défaut
    Bonjour,
    En enregistrant une macro, le code donne à peu près ceci
    Modifier les chemins et noms de dossier
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
     With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;E:\fichier à transformer en excel .txt", Destination:=Range("$A$1"))
            .Name = "fichier à transformer en excel "
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 1252
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierNone
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
     
        ActiveWorkbook.SaveAs Filename:="E:\Classeur2.xlsx", FileFormat:= _
            xlWorkbookNormal, CreateBackup:=False

  7. #7
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    Salut, en reprenant le code donné plus haut et avec le minimum de modifications

  8. #8
    Membre régulier
    Profil pro
    Inscrit en
    Janvier 2008
    Messages
    460
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2008
    Messages : 460
    Points : 71
    Points
    71
    Par défaut
    Tout d 'abord merci pour votre aide j y vois un plus clair !!! impec!!! le seul petit pb j 'ai unE ERREUR au niv de l import
    la macro bloque et il importe les données sur la ligne 1 uniquement à l horizontal de A 1 à IU 1

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ShDatas.Cells(iRow, iCol) = Ar(i)
    comment faire pour que cela face un tableau et non pas une ligne merci

  9. #9
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    re, avec le fichier de test que tu as fourni plus haut cela fonctionne sans problèmes

Discussions similaires

  1. Réponses: 0
    Dernier message: 07/06/2010, 16h01
  2. importer automatiquement des fichier txt
    Par joe370 dans le forum VBA Access
    Réponses: 1
    Dernier message: 13/06/2007, 15h39
  3. Réponses: 2
    Dernier message: 26/01/2007, 14h58
  4. [Tableaux] transformation d'un fichier txt en xml
    Par edophie dans le forum Langage
    Réponses: 1
    Dernier message: 26/09/2006, 12h55
  5. créer automatiquement un fichier txt d'un quickreport
    Par bertrand_declerck dans le forum Bases de données
    Réponses: 7
    Dernier message: 02/08/2005, 16h00

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo