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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| Option Compare Database
Option Explicit
Const tblOrigine As String = "maTable"
Const tblDestination As String = "T_result"
Public Function analyseCroisee()
Dim strSQL As String
Dim rst As DAO.Recordset
Dim rst2 As DAO.Recordset
Dim boolUpdate As Boolean
creerTableDestination tblDestination
Set rst = CurrentDb.OpenRecordset("SELECT [Ref-NPS], Marque, Ref FROM " & tblOrigine & ";")
' Pour chaque enregistrement de la table d'origine
While Not rst.EOF
boolUpdate = False
' On sélectionne les lignes dans la table de destination où [Ref-NPS] a la même valeur
Set rst2 = CurrentDb.OpenRecordset("SELECT * FROM " & tblDestination & " WHERE [Ref-NPS]='" & rst(0) & "';")
' Pour chacune de ces lignes
Do While Not rst2.EOF
' Si le champ correspondant à la marque est vide
If IsNull(rst2(Replace(rst(1), ".", "_"))) Then
' On le remplit grâce à une mise à jour du champ
rst2.Edit
rst2(Replace(rst(1), ".", "_")) = rst(2)
rst2.Update
boolUpdate = True
Exit Do
End If
rst2.MoveNext
Loop
' S'il n'y a pas eu de mise à jour du champ correspondant à la marque
If Not boolUpdate Then
' On insère une nouvelle ligne dans la table de destination
strSQL = "INSERT INTO " & tblDestination & " ([Ref-NPS],[" & Replace(rst(1), ".", "_") & "]) " & _
"VALUES ('" & rst(0) & "','" & rst(2) & "');"
CurrentDb.Execute (strSQL)
End If
rst.MoveNext
Wend
Set rst = Nothing: Set rst2 = Nothing
End Function
Private Function creerTableDestination(strTableDestination As String)
Dim rst As DAO.Recordset
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
' Création de la table de destination
If TableExiste(strTableDestination) Then DoCmd.DeleteObject acTable, strTableDestination
DoCmd.RunSQL ("CREATE TABLE " & strTableDestination & ";")
' Création des champs de la table de destination
With CurrentDb
.TableDefs.Refresh
Set rst = .OpenRecordset("SELECT DISTINCT Marque FROM " & tblOrigine & ";")
Set tdf = .TableDefs(strTableDestination)
End With
Set fld = tdf.CreateField("Ref-NPS", dbText, 55)
tdf.Fields.Append fld
While Not rst.EOF
Set fld = tdf.CreateField(Replace(rst(0), ".", "_"), dbText, 55)
tdf.Fields.Append fld
rst.MoveNext
Wend
' Libération des variables
Set rst = Nothing: Set tdf = Nothing: Set fld = Nothing
End Function
Public Function TableExiste(ByVal strTable As String) As Boolean
Dim tdf As DAO.TableDef
' Parcourir toutes les tables de la base
For Each tdf In CurrentDb.TableDefs
If tdf.Name = strTable Then
' La table a été trouvée...
TableExiste = True
Exit Function
End If
Next
' La table n'existe pas...
TableExiste = False
End Function |
Partager