Sub AddCode()
If Not ProcedureExists("Worksheet_SelectionChange", ActiveSheet) Then
With ActiveWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule
.InsertLines 2, "Private Sub Worksheet_SelectionChange(ByVal Target As Range)"
.InsertLines 3, " 'Code cua ban dat o day"
.InsertLines 4, "End Sub"
End With
Else
MsgBox "Worksheet_SelectionChange da ton tai"
End If
End Sub
Function ProcedureExists(subName As String, wh As Worksheet) As Boolean
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim LineNum As Long
Dim procName As String
Dim ProcKind As VBIDE.vbext_ProcKind
ProcedureExists = False
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents(wh.CodeName)
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CountOfDeclarationLines + 1
Do Until LineNum >= .CountOfLines
procName = .ProcOfLine(LineNum, ProcKind)
If UCase(subName) = UCase(procName) Then
ProcedureExists = True
Exit Do
End If
LineNum = .ProcStartLine(procName, ProcKind) + .ProcCountLines(procName, ProcKind) + 1
Loop
End With
End Function