Seb
Seb

Reputation: 520

Dealing with special characters in String

I am downloading some files which have some chineses characters sometimes and apparently String doesn't recognize them.

Any ideas on how I could tell VBA the following :

If there are some unknown characters in the filename then delete them and only keep the first part of the filename which contains normal characters.

Actually each of those special characters will be replaced by a "?".

But the problem is that Msgbox InStr(1, AttachmentName, "?") will return 0 even though MsgBox AttachmentName will display some "?".

I did the following, but as I said above, the "?" are displayed on MsgBox but not truly there so it never satisfies the condition...

If InStr(1, AttachmentName, "?") <> 0 Then
     AttachmentName = Mid(AttachmentName, 1, InStr(1, AttachmentName, "?") - 1) & "unknown characters "
End If

Upvotes: 0

Views: 2876

Answers (1)

Variatus
Variatus

Reputation: 14373

This sub removes all Chinese characters from a string.

Private Sub RemoveChinese()

    Dim Fun As String
    Dim Txt As String
    Dim Ch As String
    Dim n As Integer

    Txt = Selection.Text

    For n = 1 To Len(Txt)
        Ch = Mid(Txt, n, 1)
        If Asc(Ch) = AscW(Ch) Then Fun = Fun & Ch
    Next n

    MsgBox Fun
End Sub

The point is that Chinese characters are represented by 2 bytes whereas it takes only one to write a Latin character. You must have Chinese language support installed on your computer in order to be able to actually depict them. Hence the ? inserted for unrecognised characters.

Upvotes: 4

Related Questions