Hi,
you need a reference to
Microsoft Visual Basic for Applications Extensibility.
Here a very basic example,
which is a search for a word rather than
a search for a name of a sub. Anyway, renaming
subs programmatically, I think, would not be
an everyday task. Except when playing with some
malicious code.
Sub RenameSub()
Dim aMdl As VBComponent
Dim aPrj As VBProject
Dim iLin As Integer
Dim NameOld$, NameNew$
NameOld$ = "Test444"
NameNew$ = "Test444new"
Set aPrj = Application.VBE.VBProjects("Normal")
Set aMdl = aPrj.VBComponents("NewMacros")
With aMdl.CodeModule
On Error GoTo notfound
iLin = .ProcBodyLine(NameOld$, ProcKind:=vbext_pk_Proc)
'Line containing NameOld$
.ReplaceLine Line:=iLin, String:="Sub " & NameNew$ & "()"
End With
Exit Sub
notfound:
MsgBox "not found"
End Sub
If NameOld$ contains a space, the string is not
found. If it isn't found, you would get an error
"Sub or function not defined". Very strange!
-
Thanks to Christian Freßdorf and Uwe Marx.