Saturday 31 March 2012

Find and replace VBA code using VBA

It is sometimes necessary to update your code, a quick find and replace (Ctrl+H) will often be enough.  I’d also recommend the MZ Tools VBE toolbar, it has a lot to add to your VBA coding experience, including a very good search tool.

Sometimes the above is not quite want you want.  So below is a simple bit of code you can use to replace one line of code for another.

Public Sub FindAndReplace()
'-----------------------------------------------------------------------------' Procedure : FindAndReplace
' Purpose   : Searches the active workbook for a specific code line and
'             replaces it with a new code line
'-----------------------------------------------------------------------------
    Dim SL As Long, EL As Long, SC As Long, EC As Long
    Dim S As String
    Dim Found As Boolean
    Dim sFind As String
    Dim sReplace As String

    sFind = "my old line of code"
    sReplace = "my new line of code"

    With ActiveWorkbook.VBProject.VBComponents("MyCodeModule").CodeModule
        SL = 1
        SC = 1
        EL = 99999
        EC = 999
        Found = .Find(sFind, SL, SC, EL, EC, True, False, False)
        If Found = True Then
            S = .Lines(SL, 1)
            S = Replace(S, sFind, sReplace)
            .ReplaceLine SL, S
        End If
    End With

End Sub

SL / SC is the start line / start column and EL / EC is the end line / end column.  These can be changed to target code lines within a specific part of your code.

I hope the above proves useful.  As always, any questions let us know via the comments.

4 comments:

  1. What if you just wanted to replace only one word in your line of code?

    So, for example, if you had a line

    Worksheets("Sheet1").select

    and you wanted to replace "Sheet1" with "LName"

    So the new line would look like

    Worksheets("LName").select

    ReplyDelete
  2. Hi, welcome to the blog.
    The same code above will work for that need. The code can replace a single word or an entire line of code.

    ReplyDelete
  3. So, I would put:

    sFind: "Sheet1"
    sReplace: "frmUserForm.cboLName.text"

    and it would replace "Sheet1" with the value of what the ComboBox selection is from the user form?

    Am I understanding that correctly?

    Also, where you have:

    With ActiveWorkbook.VBProject.VBComponents("MyCodeModule").CodeModule

    I would replace "MyCodeModule" with what ever the form is that I'm trying to replace the code in right?

    So it would be like:

    With ActiveWorkbook.VBProject.VBComponents("frmUserForm2").CodeModule?

    ReplyDelete
  4. It is a delight to read this article. Care with excellence at no terms and condition is your priority and seem beneficial for the mankind. Great work. Keep going. Thanks

    ReplyDelete

Please, no purely anonymous comments, they will be deleted; always use a name for ease of reference by other commenters.