Découper un fichier texte .txt en plusieurs fichiers excel
Dernière réponse : dans Programmation
Bonjour,
J'ai un fichier .txt qui contient 300 000 lignes. J'ai besoin de le mettre sous excel.
Comment faire pour créer automatiquement un premier fichier avec les 65 536 premières lignes, un autre avec les 65536 suivantes ... et appeler ces fichiers "Fichier 1", "Fichier 2" ...
Je voudrais un truc style une macro parce que ça m'arrive souvent.
Merci beaucoup pour votre aide
J'ai un fichier .txt qui contient 300 000 lignes. J'ai besoin de le mettre sous excel.
Comment faire pour créer automatiquement un premier fichier avec les 65 536 premières lignes, un autre avec les 65536 suivantes ... et appeler ces fichiers "Fichier 1", "Fichier 2" ...
Je voudrais un truc style une macro parce que ça m'arrive souvent.
Merci beaucoup pour votre aide
Autres pages sur : decouper fichier texte txt plusieurs fichiers excel
Lassé par la pub ? Créez un compte
via Google j'ai trouvé cela
Option Explicit
Sub ImportLargeFile()
Dim strFilePath As String, strFilename As String, vFullPath As Variant
Dim lngCounter As Long
Dim oConn As Object, oRS As Object, oFSObj As Object
vFullPath = Application.GetOpenFilename("Text Files (*.txt),*.txt", , "Please select text file...")
If vFullPath = False Then Exit Sub
Application.ScreenUpdating = False
Set oFSObj = CreateObject("Scripting.FileSystemObject")
strFilePath = oFSObj.GetFile(vFullPath).ParentFolder.Path
strFilename = oFSObj.GetFile(vFullPath).Name
Set oConn = CreateObject("ADODB.CONNECTION")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFilePath & ";" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"""
Set oRS = CreateObject("AdoDb.Recordset")
oRS.Open "SELECT * FROM " & strFilename, oConn, 3, 1, 1
While Not oRS.EOF
Sheets.Add
ActiveSheet.Range("A1").CopyFromRecordset oRS, 65536
Wend
oRS.Close
oConn.Close
Application.ScreenUpdating = True
End Sub
Option Explicit
Sub ImportLargeFile()
Dim strFilePath As String, strFilename As String, vFullPath As Variant
Dim lngCounter As Long
Dim oConn As Object, oRS As Object, oFSObj As Object
vFullPath = Application.GetOpenFilename("Text Files (*.txt),*.txt", , "Please select text file...")
If vFullPath = False Then Exit Sub
Application.ScreenUpdating = False
Set oFSObj = CreateObject("Scripting.FileSystemObject")
strFilePath = oFSObj.GetFile(vFullPath).ParentFolder.Path
strFilename = oFSObj.GetFile(vFullPath).Name
Set oConn = CreateObject("ADODB.CONNECTION")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFilePath & ";" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"""
Set oRS = CreateObject("AdoDb.Recordset")
oRS.Open "SELECT * FROM " & strFilename, oConn, 3, 1, 1
While Not oRS.EOF
Sheets.Add
ActiveSheet.Range("A1").CopyFromRecordset oRS, 65536
Wend
oRS.Close
oConn.Close
Application.ScreenUpdating = True
End Sub
Je ne connais pas les fonctions VB* correspondantes à ces explications, mais il est tout à fait possible de lire par une boucle un nombre définit de lignes, et de les copier dans un fichier qui sera créé automatiquement.
En gros, il te faut :
une boucle qui t'avertisse quand tu as atteint la fin du fichier
une boucle qui incrémente le nom du fichier et qui le crée par le même occasion
une boucle qui lit dans le fichier de départ un nombre définit de lignes et qui les copies dans le fichier créé et ouvert.
Voilà
En gros, il te faut :
Voilà
>> Steph05 : Si au lieu de gloser tu l'essayais ... ou simplement lisais ....
"This macro example assumes that your VBA project has added a reference to the ADO object library.
You can do this from within the VBE by selecting the menu Tools, References and selecting Microsoft ActiveX Data Objects x.x Object Library." en bas du lien donné
"This macro example assumes that your VBA project has added a reference to the ADO object library.
You can do this from within the VBE by selecting the menu Tools, References and selecting Microsoft ActiveX Data Objects x.x Object Library." en bas du lien donné
Bonjour
Encore un petit détail. Si mon fichier txt contient des nombres longs (20 chiffres), quand ils se collent dans excel, ils s'écrivent en format scientifique. Comment faire un collage spécial format pour coller en texte, et ainsi garder mes nombres au bon format ?
Si j'ai par exemple, 1111111111111111111, je voudrais qu'il reste exactement écrit comme ça.
D'habitude, je fais PAsteSpecial mais là je ne sais pas où le mettre dans le code.
Merci
Encore un petit détail. Si mon fichier txt contient des nombres longs (20 chiffres), quand ils se collent dans excel, ils s'écrivent en format scientifique. Comment faire un collage spécial format pour coller en texte, et ainsi garder mes nombres au bon format ?
Si j'ai par exemple, 1111111111111111111, je voudrais qu'il reste exactement écrit comme ça.
D'habitude, je fais PAsteSpecial mais là je ne sais pas où le mettre dans le code.
Merci
OOOOOOOOOOHHHHHHH !!!!
C'est le B A BA
Sous Excel Menu Outils | Macro | Nouvelle Macro cliquer sur OK
Sélectionner la colonne et faire les manips de formatage
quand c'est fini arrêter l'enregistreur de macro
Menu Outils | Macro | Arrêter la Macro ou cliquer sur le carré bleu
Après il faudra optimiser manuellement le code généré
C'est le B A BA
Sous Excel Menu Outils | Macro | Nouvelle Macro cliquer sur OK
Sélectionner la colonne et faire les manips de formatage
quand c'est fini arrêter l'enregistreur de macro
Menu Outils | Macro | Arrêter la Macro ou cliquer sur le carré bleu
Après il faudra optimiser manuellement le code généré
Autre question que veux-tu faire de ses données ? sur un autre forum il y a un cas de fichier texte encore plus énorme et en fait l'utilisateur veut une moyenne des données de ses colonnes, cela permet en fait de ne pas importer les données texte mais de les traiter à la volée.Ne serait-ce pas ton cas ?
Je ne savais pas que ça s'appelait comme ça! Je le faisais sans savoir.
Je l'ai donc fait et ça me donne:
Columns("A:A").Select
Selection.NumberFormat = "@"
Mais ça ne marche pas.
En fait, ce sont des identifiants clients. Il existe plusieurs classes de clients reconnaissables au 1ers chiffres de l'identifiant.
Je veux donc ensuite regrouper les clients d'une même classe. La suite ça va, il ne me manque qu'à pouvoir copier mes chiffres en chiffres.
Je l'ai donc fait et ça me donne:
Columns("A:A").Select
Selection.NumberFormat = "@"
Mais ça ne marche pas.
En fait, ce sont des identifiants clients. Il existe plusieurs classes de clients reconnaissables au 1ers chiffres de l'identifiant.
Je veux donc ensuite regrouper les clients d'une même classe. La suite ça va, il ne me manque qu'à pouvoir copier mes chiffres en chiffres.
il faudrait que ces identifiants sur 20 digits se présentent dans le fichier texte sous la forme '12345678901234567890 pour qu'ils soient importés correctement sous Excel
Il reste à faire une moulinette sous Excel qui transcrive cela avant le traitement , ces identifiants sont uniquement dans la colonne A ?
Il reste à faire une moulinette sous Excel qui transcrive cela avant le traitement , ces identifiants sont uniquement dans la colonne A ?
Vite fait donc à tester, sans réponse j'ai supposé que la colonne A était la colonne concernée, que le séparateur était un point virgule ?
Sub Moulinette()
Dim Chaine As String
Dim NomFichierLu As String, NomFichierCorrige As String
Dim Debut As Variant
Dim Ar() As String
Close
Debut = Time
Application.StatusBar = ""
NomFichierLu = ThisWorkbook.Path & "\" & "Essai.txt"
NomFichierCorrige = ThisWorkbook.Path & "\" & "EssaiCor.txt"
Open NomFichierLu For Input As #1
Open NomFichierCorrige For Output As #2
Do
Line Input #1, Chaine
Ar = Split(Chaine, ";")
Ar(0) = "'" & Ar(0)
Print #2, Join(Ar, ";")
Loop Until EOF(1)
Close #2
Close #1
Application.StatusBar = "Terminé : " & Format((Time() - Debut) * 100000, "0.00")
End Sub
Sub Moulinette()
Dim Chaine As String
Dim NomFichierLu As String, NomFichierCorrige As String
Dim Debut As Variant
Dim Ar() As String
Close
Debut = Time
Application.StatusBar = ""
NomFichierLu = ThisWorkbook.Path & "\" & "Essai.txt"
NomFichierCorrige = ThisWorkbook.Path & "\" & "EssaiCor.txt"
Open NomFichierLu For Input As #1
Open NomFichierCorrige For Output As #2
Do
Line Input #1, Chaine
Ar = Split(Chaine, ";")
Ar(0) = "'" & Ar(0)
Print #2, Join(Ar, ";")
Loop Until EOF(1)
Close #2
Close #1
Application.StatusBar = "Terminé : " & Format((Time() - Debut) * 100000, "0.00")
End Sub
Toujours pas de signes de vie ... Donc une solution à adapter
( Colonne à traiter, Lettre ou pas )
'==================================================================================
' VBA Menu Outils | Références
' cocher Microsoft Scripting Runtime
' cocher Microsoft ActiveX Data Objects 2.8 Library
'==================================================================================
Option Explicit
Dim sCheminFichier As String
Dim sNomFichier As String
Sub ImportGrosFichierTxt()
Dim Fichier As Variant
Dim Conn As ADODB.Connection
Dim Rs As ADODB.RecordSet
Dim FSO As Scripting.FileSystemObject
Dim Debut As Variant
Const NbLignes As Long = 65536
Fichier = Application.GetOpenFilename("Text Files (*.txt),*.txt")
If Fichier = False Then Exit Sub
Application.StatusBar = ""
Debut = Time
Application.ScreenUpdating = False
Set FSO = New Scripting.FileSystemObject
sCheminFichier = FSO.GetFile(Fichier).ParentFolder.Path
sNomFichier = FSO.GetFile(Fichier).Name
Set FSO = Nothing
Moulinette sCheminFichier & "\" & sNomFichier
Set Conn = New ADODB.Connection
Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sCheminFichier & ";" & _
"Extended Properties=""text;" & _
"HDR=No;" & _
"FMT=Delimited"""
Set Rs = New ADODB.RecordSet
Rs.Open "SELECT * FROM " & sNomFichier, Conn, 3, 1, 1
While Not Rs.EOF
Sheets.Add
ActiveSheet.Range("A1").CopyFromRecordset Rs, NbLignes
Wend
Rs.Close
Conn.Close
Set Rs = Nothing
Set Conn = Nothing
Application.StatusBar = "Terminé : " & Format((Time() - Debut) * 100000, "0.00")
Application.ScreenUpdating = True
End Sub
Private Sub Moulinette(ByVal NomFichier As String)
Dim Chaine As String
Dim NomFichierLu As String, NomFichierCorrige As String
Dim Ar() As String
Const sSep As String * 1 = ";"
Close
NomFichierLu = NomFichier
NomFichierCorrige = sCheminFichier & "\" & "EssaiCor.txt"
Open NomFichierLu For Input As #1
Open NomFichierCorrige For Output As #2
Do
Line Input #1, Chaine
Ar = Split(Chaine, sSep)
Ar(0) = "'" & Ar(0)
Print #2, Join(Ar, sSep)
Loop Until EOF(1)
Close #2
Close #1
Kill NomFichierLu
Name NomFichierCorrige As NomFichier
End Sub
( Colonne à traiter, Lettre ou pas )
'==================================================================================
' VBA Menu Outils | Références
' cocher Microsoft Scripting Runtime
' cocher Microsoft ActiveX Data Objects 2.8 Library
'==================================================================================
Option Explicit
Dim sCheminFichier As String
Dim sNomFichier As String
Sub ImportGrosFichierTxt()
Dim Fichier As Variant
Dim Conn As ADODB.Connection
Dim Rs As ADODB.RecordSet
Dim FSO As Scripting.FileSystemObject
Dim Debut As Variant
Const NbLignes As Long = 65536
Fichier = Application.GetOpenFilename("Text Files (*.txt),*.txt")
If Fichier = False Then Exit Sub
Application.StatusBar = ""
Debut = Time
Application.ScreenUpdating = False
Set FSO = New Scripting.FileSystemObject
sCheminFichier = FSO.GetFile(Fichier).ParentFolder.Path
sNomFichier = FSO.GetFile(Fichier).Name
Set FSO = Nothing
Moulinette sCheminFichier & "\" & sNomFichier
Set Conn = New ADODB.Connection
Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sCheminFichier & ";" & _
"Extended Properties=""text;" & _
"HDR=No;" & _
"FMT=Delimited"""
Set Rs = New ADODB.RecordSet
Rs.Open "SELECT * FROM " & sNomFichier, Conn, 3, 1, 1
While Not Rs.EOF
Sheets.Add
ActiveSheet.Range("A1").CopyFromRecordset Rs, NbLignes
Wend
Rs.Close
Conn.Close
Set Rs = Nothing
Set Conn = Nothing
Application.StatusBar = "Terminé : " & Format((Time() - Debut) * 100000, "0.00")
Application.ScreenUpdating = True
End Sub
Private Sub Moulinette(ByVal NomFichier As String)
Dim Chaine As String
Dim NomFichierLu As String, NomFichierCorrige As String
Dim Ar() As String
Const sSep As String * 1 = ";"
Close
NomFichierLu = NomFichier
NomFichierCorrige = sCheminFichier & "\" & "EssaiCor.txt"
Open NomFichierLu For Input As #1
Open NomFichierCorrige For Output As #2
Do
Line Input #1, Chaine
Ar = Split(Chaine, sSep)
Ar(0) = "'" & Ar(0)
Print #2, Join(Ar, sSep)
Loop Until EOF(1)
Close #2
Close #1
Kill NomFichierLu
Name NomFichierCorrige As NomFichier
End Sub
Lassé par la pub ? Créez un compte
- Contenus similaires :
- ForumFichier excel en fichiers txt
- ForumMacro fichier texte excel
- ForumLister tous les fichiers dans fichier texte
- ForumCrã er fichier texte excel
- ForumGã nã rer fichier texte excel
- ForumDã couper un fichier txt en plusieurs fichiers
- ForumCrã ation fichier texte excel
- ForumGenerer fichier texte excel
- ForumCreer un fichier texte depuis excel
- ForumExporter un fichier excel en fichier texte
- Voir plus