dj001
dj001

Reputation: 21

How do I remove emojis from an excel sheet using VBA?

I have a spreadsheet that contains emojis, e.g., 😃, and I am looking for a solution to use Excel VBA to replace the emojis with null.

Emojis can be removed using the Excel replace action, so I recorded a macro to automate the replace. I opened the recorded macro and it was displayed as follows:

Sub Remove_Emojis()

    Cells.Replace What:="??", Replacement:="", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
End Sub

The problem is that VBA doesn't recognize emojis (😃) and replaces them with "??", i.e., Unicode characters above a certain value are not recognized by VBA.

I tried replacing "??" with ChrW():

Sub Remove_Emojis()

    Cells.Replace What:=ChrW(128515), Replacement:="", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
End Sub

but this results in an error:

Invalid procedure call of argument

because the ChrW() function does not allow a value above 65535. Note: The ChrW() function works if the value of the argument is within the range -32,767 to 65,535.

I expect that there should be support for doing this in VBA given that it can be done in Excel.

Upvotes: 0

Views: 2521

Answers (2)

dj001
dj001

Reputation: 21

Thank you to FunThomas for pointing out that emojis are represented as 2 characters in VBA. The revised VBA code that works based on this:

Sub Remove_Emojis()

    Cells.Replace What:=ChrW(-10197) & ChrW(-8701), Replacement:="", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=True, SearchFormat:=False, ReplaceFormat:=False
End Sub

In my actual solution, I put this into a loop to remove all of the different emojis.

Upvotes: 2

FunThomas
FunThomas

Reputation: 29511

I did as small experiment, putting your smiley into excel and let the following code run:

Dim s
s = ActiveCell
Dim i As Long
For i = 1 To Len(s)
    Dim c
    c = Mid(s, i, 1)
    Debug.Print i, c, AscW(c)
Next i

My result was

 1            ?             -10179 
 2            ?             -8701 

So obviously, the single character is split into 2 inside VBA. AscW and it's pendant ChrW deal with 16bit, and the emoji is a 32bit char, so in VBA this emoji character is handled as if there are 2 characters in the string

I added the following code and voilà, the smiley char was gone:

Dim x
x = ChrW(-10179) & ChrW(-8701)

s = Replace(s, x, "(smiley)")
ActiveCell.Offset(0, 1) = s

Probably you have to experiment with the different emojis you are facing and build a list in your replacing routine.

Upvotes: 10

Related Questions