vba search replace character

1.4k views Asked by At

I'm trying to prepare a spreadsheet for a report in excel vba. Unforturnately there are some wierd characters here that need to be replaced. Easy enough, except for this chracter:

  ¦

I can't seem to be able to paste that character into the editor into a string replace function. When I try, the output is _. I then thought to refer to it by it's Chr code. A quick look up said it was Chr(166). http://www.gtwiki.org/mwiki/?title=VB_Chr_Values

Replace(s, "â€" + Chr(166), "...")

But this is not that character at all (at least on Mac excel). I tried:

For i = 1 To 255
   Debug.Print Chr(i)
Next i

And I didn't see this character anywhere. Does anyone know how I can reference this character in vba code in order to replace it?

3

There are 3 answers

0
brettdj On BEST ANSWER

Not sure if is available for , but you could simplify your existing code greatly as below.

Uses a sample Strin

Dim strIn As String
strIn = "1â€1â€x123"
Do While InStr(strIn, "â€") > 0
Mid$(strIn, InStr(strIn, "â€"), 3) = "..."
Loop
1
Gary's Student On

Click on a cell containing your miscreant character and run this small macro:

Sub WhatIsIt()
    Dim s As String, mesage As String
    Dim L As Long
    s = ActiveCell.Text
    L = Len(s)
    For i = 1 To L
        ch = Mid(s, i, 1)
        cd = Asc(ch)
        mesage = mesage & ch & "     " & cd & vbCrLf
    Next i
    MsgBox mesage
End Sub

It should reveal the characters in the cell and their codes.

1
mango On

It's dirty, but here's the workaround that I used to solve this problem. I knew that my issue character was always after "â€", so the idea was to replace the character that came after those 2. I don't really know how to replace a character at a position in a string, so my idea was to covert the string to an array of characters and replace the array at those specific indexes. Here's what it looks like:

Do While InStr(s, "â€") > 1
    num2 = InStr(s, "â€")
    arr = stringToArray(s)
    arr(num2 - 1) = "<~>"
    arr(num2) = "<~>"
    arr(num2 + 1) = "<~>"

    s = Replace(arrayToString(arr), "<~><~><~>", "...")
Loop

...


Function stringToArray(ByVal my_string As String) As Variant
    Dim buff() As String
    ReDim buff(Len(my_string) - 1)
    For i = 1 To Len(my_string)
        buff(i - 1) = Mid$(my_string, i, 1)
    Next
stringToArray = buff
End Function

Function arrayToString(ByVal arr As Variant) As String
Dim s As String
    For Each j In arr
        s = s & j
    Next j
arrayToString = s
End Function

In practice, what I replaced those indexes with is something that had to be unique but recognizable. Then i can replace my unique characters with whatever I want. There are sure to be edge cases, but for now it gets the job done. stringToArray function pulled from: Split string into array of characters?