-1

Regarding VBE. If a worksheet does not exist it will create it and add a commandbutton at Sheet1. It will also add the appr. code for the private sub commandbutton1_click. This works all fine. This is part of the existing code that will add a new sub:

Dim Code as String
Code = "Private sub CommandButton1_Click()" & vbCrLf
[..]
Code = Code & "End Sub"

With ThisWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule
    .insertlines .CountOfLines + 1, Code

However before adding that 'sub code', it should check if in the already existing (object) the sub code (for commandbutton1) already exists and if so, then delete it before adding new code.

ni_hao
  • 404
  • 2
  • 5
  • 16

2 Answers2

0

have a look below.

If ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule.CountOfLines <> 0 Then
    ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule.DeleteLines 1, ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule.CountOfLines
End If
Karthick Gunasekaran
  • 2,697
  • 1
  • 15
  • 25
0

The following works for me, change the sub name as needed:

Dim VBCodeMod As CodeModule
Dim StartLine As Long
Dim HowManyLines As Long
Set VBCodeMod = Workbooks(1).VBProject.VBComponents("Sheet1").CodeModule
With VBCodeMod
    StartLine = .ProcStartLine("Worksheet_BeforeRightClick", vbext_pk_Proc)
    HowManyLines = .ProcCountLines("Worksheet_BeforeRightClick", vbext_pk_Proc)
    .DeleteLines StartLine, HowManyLines
End With
BertB
  • 108
  • 1
  • 9