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
| 'Nécessite d'activer la référence
'Microsoft "Visual basic For Application Extensibility 5.3"
Sub Macro1()
Dim Wb As Workbook
Dim Chemin As String, Fichier As String, MdP As String
Dim vbProj As Object
Dim vbComp As VBComponent
Dim x As Integer
Chemin = "C:\Users\user\Desktop\" '!!!!A adapter
Fichier = "test1.xlsm" '!!!!A adapter
MdP = "toto" '!!!!A adapter
'OUVERTURE FICHIER A TRAITER-------------------------------------------
Set Wb = Workbooks.Open(Chemin & Fichier)
'DEPROTECTION----------------------------------------------------------
Set vbProj = Wb.VBProject
If vbProj.Protection = 1 Then
Set Application.VBE.ActiveVBProject = vbProj
SendKeys MdP & "~~"
Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
MsgBox "Deprotection ok"
End If
'ECRITURE CODE SI INEXISTANT--------------------------------------------
Set vbComp = Wb.VBProject.VBComponents.Item("Feuil1") '!!!!Feuil1 est le CodeName de la feuille et non son Name
With vbComp.CodeModule
x = .CountOfLines
If Not .Find("Worksheet_SelectionChange", 1, 1, .CountOfLines, 3) Then
.InsertLines x + 1, "Private Sub Worksheet_SelectionChange(ByVal Target As Range)"
.InsertLines x + 2, "Dim NumeroAliment As String"
.InsertLines x + 4, " If Target.Column = 1 And Target.Row > 2 And Target.Count = 1 Then"
.InsertLines x + 5, " NumeroAliment = Target.Value"
.InsertLines x + 6, " Module2.définitive (NumeroAliment)"
.InsertLines x + 7, " End If"
.InsertLines x + 8, "End Sub"
MsgBox "Ecriture code ok"
Else
MsgBox "Code déjà existant"
End If
End With
Set vbComp = Nothing
'PROTECTION------------------------------------------------------------
DoEvents
SendKeys "+{TAB}{RIGHT}%V{+}{TAB}" & MdP & "{TAB}" & MdP & "~"
Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
DoEvents
MsgBox "Protection ok"
'SAUVEGARDE ET FEMETURE-------------------------------------------------
Set vbProj = Nothing
Wb.Close True
Set Wb = Nothing
MsgBox "Opération terminée avec succès"
End Sub |