Public Sub CsvToTxt()
'déclaration des variables
Dim pathFichierCsv As String, pathFichierTxt As String, tabEl() As String, ligneTxt As String
Dim myFso As Object, fichierCsv As Object, fichierTxt As Object
'définition des variables
pathFichierCsv = "E:\XLS\test\TEST_fichier.csv" 'fichier .csv (à lire)
pathFichierTxt = "E:\XLS\test\TEST_fichier2.txt" 'fichier .txt (à écrire)
'ouvrir les deux fichiers
Set myFso = CreateObject("Scripting.FileSystemObject")
Set fichierCsv = myFso.OpenTextFile(pathFichierCsv, 1) 'ouvrir le fichier .csv en lecture seule
Set fichierTxt = myFso.CreateTextFile(pathFichierTxt, True) 'créer le fichier .txt
On Error Resume Next
'on va maintenant boucler sur chaque ligne du fichier .csv
While Not fichierCsv.AtEndOfStream
'récupérer les éléments de la ligne .csv (séparés par ;) dans un tableau
tabEl = Split(fichierCsv.ReadLine, ";")
'initialiser la ligne .txt
ligneTxt = ""
'vérifier si c'est une ligne "10" ou "20" (premier élément du tableau)
If tabEl(0) = "10" Then
'traitement spécifique à une ligne "10"
ElseIf tabEl(0) = "20" Then
'traitement spécifique à une ligne "20"
'ajouter à la ligne .txt chaque élément du tableau à une longueur spécifiée
ligneTxt = ligneTxt & FormaterTxt(tabEl(0), 2) 'premier élément, de longueur 2
ligneTxt = ligneTxt & FormaterTxt(tabEl(1), 6) '...
ligneTxt = ligneTxt & FormaterTxt(tabEl(2), 3) '...
ligneTxt = ligneTxt & FormaterTxt(tabEl(3), 8) '...
ligneTxt = ligneTxt & FormaterTxt(tabEl(4), 3)
ligneTxt = ligneTxt & FormaterTxt(tabEl(5), 8)
ligneTxt = ligneTxt & FormaterTxt(tabEl(6), 3)
ligneTxt = ligneTxt & FormaterTxt(tabEl(7), 3)
ligneTxt = ligneTxt & FormaterTxt(tabEl(8), 8)
ligneTxt = ligneTxt & FormaterTxt(tabEl(9), 8)
ligneTxt = ligneTxt & FormaterTxt(tabEl(10), 10)
ligneTxt = ligneTxt & FormaterTxt(tabEl(11), 12)
ligneTxt = ligneTxt & FormaterTxt(tabEl(12), 6)
ligneTxt = ligneTxt & FormaterTxt(tabEl(13), 6)
End If
'ajouter la ligne .txt au fichier .txt
fichierTxt.WriteLine ligneTxt
Wend
'fermer les fichiers
fichierCsv.Close: fichierTxt.Close
'détrire les objets
Set myFso = Nothing: Set fichierCsv = Nothing: Set fichierTxt = Nothing
End Sub
'Cette fonction prend en paramètre un texte et une longeur.
'Elle retourne le texte à la longeur spécifiée (tronqué ou complété d'espaces)
Private Function FormaterTxt(texte As String, longueur As Long) As String
'si le texte est aussi long que la longueur spécifiée
If Len(texte) = longueur Then
'renvoyer le texte tel quel
FormaterTxt = texte: Exit Function
'sinon, si le texte est plus long que la longueur spécifiée
ElseIf Len(texte) > longueur Then
'renvoyer le texte tronqué en partant de la gauche
FormaterTxt = Left(texte, longueur): Exit Function
'sinon, si le texte est moins long que la longueur spécifiée
ElseIf Len(texte) < longueur Then
'renvoer le texte complété d'espaces (à gauche)
FormaterTxt = Strings.String(longueur - Len(texte), " ") & texte: Exit Function
End If
End Function