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 70 71 72 73 74
| Private Sub btnExcel_Click()
On Error GoTo Err_btnExcel_Click
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fld As DAO.Field
Dim oApp As Excel.Application
Dim oWkb As Excel.Workbook
Dim oWSht As Excel.Worksheet
Dim i As Integer, l As Integer, c As Integer
Dim strSQL As String, strFeuille As String, strChemin As String, strNom As String
'Inscrire le nom du fichier choisi et son chemin
DoCmd.Hourglass True
strChemin = Parcourir
'Si aucun fichier choisi
If strChemin = "" Then: Exit Sub
'Récupérer le nom du fichier seulement
l = InStrRev(strChemin, ".")
strNom = Left(strChemin, l - 1)
l = InStrRev(strNom, "\")
strNom = Right(strNom, Len(strNom) - l)
'Choisir la bonne feuille
strFeuille = "Summary"
'Créer l'objet Excel
Set oApp = CreateObject("excel.application")
'Récupérer le fichier
Set oWkb = oApp.Workbooks.Open(strChemin)
'Récupérer la bonne feuille
Set oWSht = oWkb.Worksheets(strFeuille)
'Créer le record
Set db = CurrentDb
Set rst = db.OpenRecordset("T_Summary")
'Première ligne d'importation ici on débute sur la quatrième ligne
i = 4
'tant que la cellule A n'est pas vide
While oWSht.Range("A" & i).Value <> ""
'On ajoute une ligne dans la table
rst.AddNew
'On débute au champ # 2, le premier champ étant un numéro automatique, la numérotation commence à 0
'Donc on a pas besoin d'inscrire Access va se charger de créer un numéro automatiquement
c = 1
For c = 1 To rst.Fields.Count - 1
If c = 1 Then
'On inscrit le nom du fichier Excel dans le deuxième champ
rst.Fields(c) = strNom
Else
'On inscrit les informations de la feuille Excel à partir de la ligne 4 et colonne 1
rst.Fields(c) = oWSht.Cells(i, c - 1)
End If
Next c
rst.Update
i = i + 1
Wend
rst.Close
Set rst = Nothing
Set db = Nothing
Exit_btnExcel_Click:
oWkb.Close
Set oWSht = Nothing
Set oWkb = Nothing
Set oApp = Nothing
DoCmd.Hourglass False
Exit Sub
Err_btnExcel_Click:
If err.Number = 9 Then
'Si la feuille Summary n'est pas trouvée
MsgBox "Le nom de la feuille n'est pas valide!", vbExclamation
Else
MsgBox err.Description
End If
Resume Exit_btnExcel_Click
End Sub |
Partager