Can you post the complete code that you're using?
Please note that the below code is what I ended up using and works but not as I originally wanted it to.
I was originally trying to have a button called TestCode. This button would be used to test code. I have other buttons that would generate VBA code. Each of those buttons would, after generating VBA code, replace all the VBA code in TestCode_Click(). This I was unable to do. So I ended up putting a Macro into TestCode_Click(). The below code would delete all the Modules/Macros and create a new one and add code to Module1. This is less than ideal since I could only ever have ONE Macro as the code below would delete all Macros. I tried to limit it to deleting only Module1 but then again, if in the future I used more macros, the TestCode could never be guaranteed to be be in Module1.
Can you help me find a better solution? Thanks in advance.
Dim MobileNum As String
Dim MobileNumVariableName As String
Dim SMSTxt As String
Dim SMSTxtVariableName As String
Dim wbname As String
Dim Clipboard As MSForms.DataObject
Dim DataObj As New MSForms.DataObject
MobileNum = ThisWorkbook.Worksheets("VBA Tools").Range("I191").Value
MobileNumVariableName = ThisWorkbook.Worksheets("VBA Tools").Range("I192").Value
SMSTxt = ThisWorkbook.Worksheets("VBA Tools").Range("I193").Value
SMSTxtVariableName = ThisWorkbook.Worksheets("VBA Tools").Range("I194").Value
wbname = ThisWorkbook.Name
Code
DataObj.SetText Code
DataObj.PutInClipboard
Set cmdButton = ThisWorkbook.Worksheets("VBA Tools").Shapes("btnCodeSMS")
btnTestCode.Caption = "Test SMS "
btnTestCode.AutoSize = True
Rem Deletes Module1
On Error Resume Next
Set vbCom = Application.VBE.ActiveVBProject.VBComponents
For i = 1 To 100
vbCom.Remove VBComponent:= _
vbCom.Item("Module" & i)
Next i
Rem End of Delete Module 1
Code = "Sub TestCode()" & vbLf & Code & vbLf & vbLf & "End Sub"
Dim vbp As Object
Dim newmod As Object
Set vbp = ActiveWorkbook.VBProject
Set newmod = vbp.VBComponents.Add(1)
Dim StartLine As Long
Dim cLines As Long
On Error Resume Next
With ActiveWorkbook.VBProject.VBComponents("Module1").CodeModule
cLines = .CountOfLines + 1
.InsertLines cLines, Code
End With