Sub ImportCSVWithDynamicColumnsB()
Dim ws As Worksheet
Dim filePaths As Variant
Dim qt As QueryTable
Dim firstLine As String
Dim colCount As Integer
Dim colDataTypes() As Integer
Dim i As Integer
Dim FSO As Object
Dim myFile As Object
Dim lastRow As Long
Dim filePath As Variant
Dim tbl As ListObject
Dim tempRange As Range
Dim newDataRange As Range
Dim VarTabtempRange As Variant
Dim startRow As Long
' Demander à l'utilisateur de sélectionner les fichiers CSV (multiselection)
filePaths = Application.GetOpenFilename("Fichiers CSV (*.csv), *.csv", , "Sélectionnez les fichiers CSV", , True)
' Vérifier si l'utilisateur a annulé la sélection
If IsArray(filePaths) = False Then Exit Sub
' la feuille active
Set ws = ThisWorkbook.Worksheets(ActiveSheet.Name)
Set tbl = ws.ListObjects("Tableau1")
' Initialiser FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
' Boucler sur chaque fichier sélectionné
For Each filePath In filePaths
' Vérifier si le fichier existe
If Dir(filePath) = "" Then
MsgBox "Le fichier n'existe pas : " & filePath, vbExclamation
Exit Sub
End If
' Lire la première ligne du fichier CSV
Set myFile = FSO.OpenTextFile(filePath, 1)
If Not myFile.AtEndOfStream Then
firstLine = myFile.ReadLine
End If
myFile.Close
' Compter le nombre de colonnes en comptant les délimiteurs ;
colCount = UBound(Split(firstLine, ",")) + 1
' Créer dynamiquement le tableau TextFileColumnDataTypes
ReDim colDataTypes(1 To colCount)
For i = 1 To colCount
colDataTypes(i) = 1 ' Importer toutes les colonnes comme texte
Next i
' Trouver la dernière ligne utilisée
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
If lastRow = 1 And ws.Cells(1, 1).Value = "" Then
lastRow = 0 ' Si la feuille est vide, commencer à la première ligne
End If
' Créer une QueryTable pour importer les données du fichier CSV
On Error GoTo ErrHandler
Set qt = ws.QueryTables.Add(Connection:="TEXT;" & filePath, Destination:=ws.Cells(lastRow + 1, 1))
' Configurer les paramètres de la QueryTable
With qt
.TextFilePlatform = 65001
.TextFileParseType = xlDelimited
'.TextFileSemicolonDelimiter = True ' Définir le délimiteur comme un point-virgule
.TextFileCommaDelimiter = True ' Définir le délimiteur comme un virgule
.TextFileColumnDataTypes = colDataTypes ' Utiliser le tableau dynamique
.Refresh BackgroundQuery:=False
' *******************************************************************************************
' Définir la plage des données importées (dans la Feuille)
Set tempRange = .ResultRange
' Ajuster la plage de la nouvelle ligne dans le tableau structuré
Set newDataRange = tbl.ListRows.Add.Range.Resize(tempRange.Rows.Count, tempRange.Columns.Count)
' Copier les données importées dans le tableau structuré
tempRange.Select
newDataRange.Select
newDataRange.Value = tempRange.Value
Rows(Cells(65536, 1).End(xlUp).Row).Delete
' *******************************************************************************************
' Suppression
.Parent.Names(.Name).Delete ' Supprimer le nom défini créé par Excel
.Delete ' Supprimer la QueryTable
End With
Next filePath
' Nettoyer
Set qt = Nothing
Set ws = Nothing
Exit Sub
ErrHandler:
MsgBox "Erreur lors de l'importation du fichier CSV : " & Err.Description, vbCritical
If Not qt Is Nothing Then
qt.Delete
Set qt = Nothing
End If
If Not ws Is Nothing Then
ws.Delete
Set ws = Nothing
End If
End Sub