Find and replace macro, longer than 99 characters

raceonusa

Board Regular
Joined
Mar 28, 2007
Messages
61
I'm trying to run a find and replace macro that replaces a word "apples" for a string of text that is 200 characters long. It always has an error when I try to make a string of text longer than 99 characters.

Is there a way to find and replace a cell with another cell depending on the text in the cell. For instance , if there is a cell with the text APPLE, is there a way to replace all cells in the column containing the word APPLE with another cell like "C2"? Maybe this would let me accomplish the long text string.

Thanks for your input.
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
This is one way :-
Code:
'=============================================================================
'- REGULAR EXPRESSION TO REPLACE ALL INSTANCES OF TEXT IN A STRING
'- A1 contains main string to be searched .... A3 gets the result
'- C2 contains text to replace. C3 contains replacement
'- This can be adapted to have the source as a text file.
'- Brian Baulsom March 2008
'=============================================================================
Sub REPLACE_TEXT()
    Dim OldText As String
    Dim ReplaceThis As String
    Dim ReplaceWith As String
    Dim MyRegExp As Object
    Dim MyPattern As String
    Dim NewText As String
    '-------------------------------------------------------------------------
    '- INITIALISE VARIABLES
    Set MyRegExp = CreateObject("VbScript.RegExp")
    OldText = Range("A1").Value
    ReplaceThis = Range("C2").Value  ' reg. expression pattern -fixed string
    ReplaceWith = Range("C3").Value
    '-------------------------------------------------------------------------
    '- EXECUTE REGULAR EXPRESSION REPLACE
    With MyRegExp
        .Global = True      ' replace every instance
        .pattern = ReplaceThis
        .ignorecase = True
        NewText = .Replace(OldText, ReplaceWith)
    End With
    '-------------------------------------------------------------------------
    '- RESULT
    Range("A3").Value = NewText
End Sub
'------------------------------------------------------------------------------
 
Upvote 0
Hi

I have a similar problem, using Excel 2003 on XP.

I have a dataset where some characters are shown as html code. I have "rsquo;"(with an extra & at the beginning of course, but if I add that, it will be read as html in my post.) instead of an apostrophe. Some of the entries which contain the "rsquo;" are longer than 99 characters, so my macro that uses

.replace What:="rsquo;", Replacement:="'", LookAt:=xlPart

(built into a loop) doesn't replace the instances that are in the long entries.

I have tried to adapt Brian's code (above), but couldn't quite figure it out. Could someone help? Or is there another solution?

I have 2 specific questions concerning Brians code:
1) Is the range in which the replacement should be made defined in A1?
2) Why is the variable NewText defined in that way? What is the macro doing with it?

Thanks, Chris
 
Upvote 0
you might want to try saving as a .csv then edit with EditPadPRO using regular expressions.. I don't know much about regex, but I wento to www.regular-expressions.info and there was some good beginner information that I could understand.
 
Upvote 0
I have to say that I do not fully understand the problem, not having had it myself. Having given a basic answer earlier on with no reply I assumed that I had supplied sufficient information.

Up to XL2000 at least (which is what I am using now) we are able to have up to 256 characters to a cell, and I have just successfully used find/replace from the menu to replace multiple instances of a string within a string of 200 characters in a cell. What are you doing different to this ?

Regular expressions basically work like this :
1. We start with a text string that we want to change somehow.
2. We supply a Regular Expression according to the rules/methods as another text string.
3. We run the Regular Expression engine and get the result as a third text string. If .Global is set to True it will replace all instances of the target string, otherwise only the first instance it finds.

For RE there is no limit to the size of a string that can be manipulated. The only limitations are those of the application running it. In the case of Excel we have a limit to the number of characters that can be contained in a cell, but there is no limit to the number of characters that can be contained in a text file.

Here are another couple of examples :-
http://www.mrexcel.com/forum/showthread.php?t=299893

Code:
'=======================================================================================
'- ACCESS A CLOSED .XLS FILE TO GET LAST USER NAME
'=======================================================================================
'- NB.1.Cannot get this by opening the workbook because we then become the last user.
'-    2.Not the same as the "Last saved by" property which requires opening the workbook.
'-    3.No security. A user can change their name temporarily in Tools/Options.
'=======================================================================================
'- Last user name is preceded by characters [\][0][p][0][??][0][0]
'- [??] is a variable character - its code shows the number of characters in the name.
'- followed by any number of spaces (and can include spaces)
'- Method : Use a Regular Expression to find the precedes + 50 following characters
'-          ..... then use the [??] character to extract the string
'- Brian Baulsom December 2007
'========================================================================================
Sub GET_LAST_USER()
    Dim MyFile As String            ' File name
    Dim MyRegExp As Object
    Dim MyLastUser                  ' last user name
    Dim LastUserLen As Integer      ' character 5 name length
    Dim FileString As String        ' file converted to a string in memory
    Dim MyMatches As Variant        ' RegExp array of matches (should only be 1)
    Dim MyLastSaved As String       ' "Last saved by" from properties
    '---------------------------------------------------------------------------------
    ChDrive "F"
    ChDir "F:\"
    MyFile = Application.GetOpenFilename("Excel Files (*.xls), *.xls")
    If MyFile = "False" Then End
    '----------------------------------------------------------------------------------
    '- PUT THE FILE INTO MEMORY AND CLOSE IT
    Open MyFile For Binary As #1
        FileString = Input(FileLen(MyFile), #1)
    Close #1
    '----------------------------------------------------------------------------------
    '- SET UP A REGULAR EXPRESSION
    Set MyRegExp = CreateObject("VbScript.RegExp")
    With MyRegExp
        .Global = True
        .pattern = "\\\x00p\x00.\x00\x00.{50}"      ' 57 characters should be enough
        Set MyMatches = .Execute(FileString)        ' zero based array
        '------------------------------------------------------------------------------
        '- DISPLAY RESULTS (should only be 1 match = Matches(0))
        '------------------------------------------------------------------------------
        '- check only 1
        If MyMatches.Count <> 1 Then
            MsgBox ("Found " & MyMatches.Count & " matches" & vbCr _
                    & "Only showing first one.")
        End If
        '------------------------------------------------------------------------------
        '- exclude first 7 characters & trailing spaces
        MyLastUser = MyMatches(0)                       ' 57 characters found
        LastUserLen = Asc(Mid(MyLastUser, 5, 1))        ' length of name
        MyLastUser = Mid(MyLastUser, 8, LastUserLen)    ' extract name
        '------------------------------------------------------------------------------
        '- Message
        rsp = MsgBox(MyFile & vbCr & "Last user was : " & MyLastUser)
        'MsgBox (MyLastUser)
        '--------------------------------------------------------------------------------
    End With
    '------------------------------------------------------------------------------------
End Sub
'========================================================================================


Hope this helps.
 
Upvote 0

Forum statistics

Threads
1,214,925
Messages
6,122,298
Members
449,077
Latest member
Rkmenon

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top