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
|
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim ligne As String 'lignes de la macro
Dim nomVB As String
Dim isVBEopen As Boolean 'true si l'editeur de macro est deja ouvert, false sinon (VBE = Visual Basic Editor)
Dim x As Long
If (Application.VBE.MainWindow.Visible = True) Then
isVBEopen = True
Else
isVBEopen = False
Application.VBE.MainWindow.Visible = True 'ouverture de l'editeur de macros pour pouvoir creer la nouvelle macro dans le classeur wb
End If
Set wb = Workbooks.Add 'ouverture d'un classeur vierge
Set ws = wb.Sheets(1)
ws.Range("A1").Value = 4
ligne = ligne & "Private Sub Worksheet_Change(ByVal Target As Range)" & vbCrLf
ligne = ligne & vbCrLf
ligne = ligne & "If (Target.AddressLocal = ""$A$1"") Then" & vbCrLf
ligne = ligne & " ActiveSheet.Range(""$A$2"").Value = ActiveSheet.Range(""$A$1"").Value + 2" & vbCrLf
ligne = ligne & "End If" & vbCrLf
ligne = ligne & vbCrLf
ligne = ligne & "End Sub"
nomVB = Sheets(ws.Name).CodeName
'ajout de la procedure dans la feuille
With wb.VBProject.VBComponents(nomVB).CodeModule
x = .CountOfLines + 1
.InsertLines x, ligne
End With
'fermeture de l'editeur de macros s'il etait initialement ferme
If (isVBEopen = False) Then Application.VBE.MainWindow.Visible = False
wb.SaveAs Filename:="C:\Temp\testMacro.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub |