Juggler_IN
Active Member
- Joined
- Nov 19, 2014
- Messages
- 358
- Office Version
- 2003 or older
- Platform
- Windows
The following subroutine replaces a single line of code with another line across the module. How can this be modified to either replace a single line with a multi-line code ir vuce versa?
Say for example, replace all occurrences of:
Application.Calculation = xlCalculationManual (single line)
with
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual (two lines of code)
VBA Code:
Sub ReplaceCodeModuleText(strModule As String, strFindWhat As String, strReplaceWith As String)
Dim VBProj As VBProject
Dim VBComp As VBComponent
Dim CodeMod As CodeModule
Dim SL As Long ' Start line
Dim EL As Long ' End line
Dim SC As Long ' Start column
Dim EC As Long ' End column
Dim strCodeLine As String
Dim vDummy As Variant
Dim Found As Boolean
Set VBProj = Application.VBE.ActiveVBProject
Set VBComp = VBProj.VBComponents(strModule)
Set CodeMod = VBComp.CodeModule
With CodeMod
SL = 1: EL = .CountOfLines
SC = 1: EC = 255
Found = .Find(Target:=strFindWhat, StartLine:=SL, StartColumn:=SC, _
EndLine:=EL, EndColumn:=EC, _
wholeword:=True, MatchCase:=False, PatternSearch:=False)
If Found Then
strCodeLine = CodeMod.Lines(SL, 1)
strCodeLine = Replace(strCodeLine, strFindWhat, strReplaceWith, Compare:=vbTextCompare) ' Not case sensitive = vbTextCompare
.ReplaceLine SL, strCodeLine
Debug.Print "Successfully Replaced: " & strFindWhat & " in VBA Module: " & strModule & " with : " & strReplaceWith
Else
Debug.Print "Did not find: " & strFindWhat;
End If
End With
End Sub
Sub Demo()
Call ReplaceCodeModuleText("Module1", "Application.Calculation = xlCalculationManual", "Application.Calculation = xlCalculationManual" & Chr(13) & Chr(10) & "Application.EnableEvents = False")
End Sub
Say for example, replace all occurrences of:
Application.Calculation = xlCalculationManual (single line)
with
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual (two lines of code)