Substitute Function in Excel VBA for cell range

SMPH picture SMPH · Jul 10, 2013 · Viewed 84.1k times · Source

I have to replace one character with another in Excel file.

I have used following Replace function, but due to exceeds of 1024 character limit in some cells, it stops there.

Sub Replace()

    With Sheets("Sheet1").Range("A1:A629")   

      .Cells.Replace ",", ";", xlPart, xlByRows, False

    End With

End Sub 

I got to know Substitute function would do

Cells(1, 2) = "=SUBSTITUTE(A1,"","","";"")"

But how do I use that for cell range?

Answer

psiphi75 picture psiphi75 · Jul 10, 2013

Try this. Note that it uses the VBA Replace function, so you need to rename your 'Replace` subroutine.

Sub ReplaceText()

    For Each c In Sheets("Sheet1").Range("A1:A629").Cells

      c = Replace(c.Value, ",", ";")

    Next c

End Sub

Note: This will only work if you have values in the cells, no Formulas. Because Excel has a formula length limit of 1024 characters. But given you have this specific error, your cells must not be formulas.