Option Explicit
Sub AddSheetWithCode()
'This code requires "trusted access to the VBE"
Dim MyVBE As Object
Dim shtCode As String
Dim sht As Worksheet
'I think this part is written by Tom Urtis
If Val(Application.Version) >= 10 Then
On Error Resume Next
Set MyVBE = ActiveWorkbook.VBProject
If Err.Number <> 0 Then
MsgBox _
"The security settings for Excel on your computer are not set to " & _
"allow you to access this macro. This security measure " & _
"deals with trusted access to the Visual Basic Editor, and was " & _
"added to versions beginning with Excel 2002." & vbNewLine & vbNewLine & _
"To establish access to this macro, follow these steps:" & vbNewLine & vbNewLine & _
"(1) Click the OK button at the bottom of this message." & vbNewLine & _
"(2) From the worksheet menu, click Tools > Macro > Security." & vbNewLine & _
"(3) Select the tab named ''Trusted Publishers''." & vbNewLine & _
"(4) Select by putting a checkmark in the box next to" & vbNewLine & _
" ''Trust access to Visual Basic Project''." & vbNewLine & _
"(5) Click the OK button to exit the Security dialog." & vbNewLine & vbNewLine & _
"After that, come back here and click button again.", _
16, "Cannot continue due to security settings - - see explanation below:"
Exit Sub
End If
End If
On Error GoTo 0
'add sheet and code
Application.ScreenUpdating = False
Set sht = ThisWorkbook.Sheets.Add
shtCode = _
"Private Sub Worksheet_SelectionChange(ByVal Target As Range)" & vbNewLine & _
"If Target.Cells.Count > 1 Then Exit Sub" & vbNewLine & _
"MsgBox ""You selected cell "" & target.address(0,0)" & vbNewLine & _
"End Sub"
ThisWorkbook.VBProject.VBComponents(sht.CodeName).CodeModule.AddFromString shtCode
Application.ScreenUpdating = True
End Sub