Voila un petit bout de code qui vérifie les noms des colonnes Excel avant d'importer un fichier dans une table Access ![;)](https://www.developpez.net/forums/images/smilies/icon_wink.gif)
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
| Sub OpenExcel(Optional ByVal pbAppVisible As Boolean)
Set AppEx = CreateObject("Excel.Application")
AppEx.Application.Visible = pbAppVisible
End Sub
Sub CloseExcel()
AppEx.Quit
Set AppEx = Nothing
End Sub
Sub ImportFichierExcel(ByVal FileName As String, ByVal TableName As String)
Dim MaFeuille As Excel.Worksheet
Dim I As Integer
Dim vbFormatOk As Boolean
OpenExcel False
AppEx.Workbooks.Open FileName
With AppEx
vbFormatOk = True
While I < CurrentDb.TableDefs(TableName).Fields.Count And vbFormatOk
If CurrentDb.TableDefs(TableName).Fields(I).Name <> .Cells(1, I + 1) Then
vbFormatOk = False
End If
I = I + 1
Wend
If vbFormatOk Then
vbFormatOk = (.Cells(1, I + 1) = "") 'test si la colonne suivante est bien vide
End If
End With
CloseExcel
If vbFormatOk Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, TableName, FileName, True
Else
MsgBox "Le format du fichier Excel n'est pas conforme !", vbExclamation
End If
End Sub |
A utiliser de la manière suivante :
ImportFichierExcel "C:\Didier\Classeur1.xls","MaTable"
Partager