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
| Sub donneeAvecExcel()
On Error GoTo GestErr
'Déclaration des variables
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim xlSh As Excel.Worksheet
Dim iR As Integer
Dim i As Integer, j As Integer
Dim oDoc As Document
Dim NoFact As Integer
Dim oTbl As Table
Dim stDocName As String
'Affectation des données aux variables
Set xlApp = New Excel.Application
Set xlWb = xlApp.Workbooks.Open("C:\Documents and Settings\Olivier\Mes documents\Mes sources de données\adresses.xlsx")
Set xlSh = xlWb.Worksheets(2)
'Récupération du nombre de lignes et de colonnes
iR = xlSh.UsedRange.Rows.Count
NoFact = 0
' Récupération des des données de la feuille pour les injecter dans le document.
For i = 2 To iR
If NoFact <> xlSh.Cells(i, 2) Then
'Test de comparaison si le résultat est vrai, on crée un nouveau document
stDocName = "c:\temp\" & xlSh.Cells(i, 2) & "-" & Format(Date, "yy-mm-dd") & ".docm"
oDoc.Close
Set oDoc = Documents.Add("C:\Documents and Settings\Olivier\Application Data\Microsoft\Templates\pub1.dotm")
oDoc.Bookmarks(1).Range.Text = xlSh.Cells(i, 1)
oDoc.Bookmarks(2).Range.Text = xlSh.Cells(i, 2)
oDoc.Bookmarks(3).Range.Text = xlSh.Cells(i, 3)
Set oTbl = oDoc.Tables(1)
oTbl.Rows.Add
oTbl.Rows.Last.Cells(1).Range.Text = xlSh.Cells(i, 4)
oTbl.Rows.Last.Cells(2).Range.Text = xlSh.Cells(i, 5)
Set oTbl = Nothing
oDoc.SaveAs stDocName
'Affectation du nouveau numéro de facture pour la comparaison
NoFact = xlSh.Cells(i, 2)
Else
'Si le résultat est faux on ajoute un ligne
Set oTbl = oDoc.Tables(1)
oTbl.Rows.Add
oTbl.Rows.Last.Cells(1).Range.Text = xlSh.Cells(i, 4)
oTbl.Rows.Last.Cells(2).Range.Text = xlSh.Cells(i, 5)
Set oTbl = Nothing
oDoc.Save
End If
Next i
oDoc.Close
Set oDoc = Nothing
GestErr:
'Si pas de document ouvert on fait un resume next
If Err.Number = 91 Then Resume Next
Debug.Print "Erreur : " & Err.Number & Err.Description
xlWb.Close
xlApp.Quit
Set xlSh = Nothing
Set xlWb = Nothing
Set xlApp = Nothing
End Sub |
Partager