Pergunta

A minha pasta de lixo eletrônico foi se enchendo de mensagens compostas no que parece ser o alfabeto cirílico. Se um corpo da mensagem ou o assunto da mensagem é em cirílico, quero excluí-lo permanentemente.

Na minha tela eu vejo caracteres cirílicos, mas quando eu percorrer a mensagens em VBA no Outlook, o "Assunto" propriedade das marcas de mensagem retorna pergunta.

Como posso determinar se o assunto da mensagem é em caracteres cirílicos?

(Nota:. Examinei a propriedade "InternetCodePage" - é geralmente da Europa Ocidental)

Foi útil?

Solução

O tipo de dados String em VB / VBA pode lidar com caracteres Unicode, mas o próprio IDE tem dificuldade para exibi-los (daí os pontos de interrogação).

Eu escrevi uma função IsCyrillic que pode ajudá-lo. A função recebe um único argumento String e retorna True se a cadeia contém pelo menos um caractere cirílico. Eu testei este código com o Outlook 2007 e parece funcionar bem. Para testá-lo, me enviou alguns e-mails com texto cirílico na linha de assunto e verificado que o meu código de teste poderia escolher corretamente a esses e-mails entre tudo na minha caixa de entrada.

Então, eu realmente tenho dois trechos de código:

  • O código que contém a função IsCyrillic. Isso pode ser cópia colado para um novo módulo VBA ou adicionado a o código que você já tem.
  • A rotina Test eu escrevi (no Outlook VBA) para testar se o código realmente funciona. Ele demonstra como usar a função IsCyrillic.

O Código

Option Explicit

Public Const errInvalidArgument = 5

' Returns True if sText contains at least one Cyrillic character'
' NOTE: Assumes UTF-16 encoding'

Public Function IsCyrillic(ByVal sText As String) As Boolean

    Dim i As Long

    ' Loop through each char. If we hit a Cryrillic char, return True.'

    For i = 1 To Len(sText)

        If IsCharCyrillic(Mid(sText, i, 1)) Then
            IsCyrillic = True
            Exit Function
        End If

    Next

End Function

' Returns True if the given character is part of the Cyrillic alphabet'
' NOTE: Assumes UTF-16 encoding'

Private Function IsCharCyrillic(ByVal sChar As String) As Boolean

    ' According to the first few Google pages I found, '
    ' Cyrillic is stored at U+400-U+52f                '

    Const CYRILLIC_START As Integer = &H400
    Const CYRILLIC_END  As Integer = &H52F

    ' A (valid) single Unicode char will be two bytes long'

    If LenB(sChar) <> 2 Then
        Err.Raise errInvalidArgument, _
            "IsCharCyrillic", _
            "sChar must be a single Unicode character"
    End If

    ' Get Unicode value of character'

    Dim nCharCode As Integer
    nCharCode = AscW(sChar)

    ' Is char code in the range of the Cyrillic characters?'

    If (nCharCode >= CYRILLIC_START And nCharCode <= CYRILLIC_END) Then
        IsCharCyrillic = True
    End If

End Function


Exemplo de Uso

' On my box, this code iterates through my Inbox. On your machine,'
' you may have to switch to your Inbox in Outlook before running this code.'
' I placed this code in `ThisOutlookSession` in the VBA editor. I called'
' it in the Immediate window by typing `ThisOutlookSession.TestIsCyrillic`'

Public Sub TestIsCyrillic()

    Dim oItem As Object
    Dim oMailItem As MailItem

    For Each oItem In ThisOutlookSession.ActiveExplorer.CurrentFolder.Items

        If TypeOf oItem Is MailItem Then

            Set oMailItem = oItem

            If IsCyrillic(oMailItem.Subject) Then

                ' I just printed out the offending subject line '
                ' (it will display as ? marks, but I just       '
                ' wanted to see it output something)            '
                ' In your case, you could change this line to:  '
                '                                               '
                '     oMailItem.Delete                          '
                '                                               '
                ' to actually delete the message                '

                Debug.Print oMailItem.Subject

            End If

        End If

    Next

End Sub

Outras dicas

a propriedade "Assunto" da mensagem retorna um monte de pontos de interrogação.

Um problema seqüência de codificação clássico. Parece que a propriedade está retornando ASCII, mas você quer UTF-8 ou Unicode.

Parece-me que você tem uma solução fácil já - basta olhar para qualquer linha de assunto com (digamos) 5 pontos de interrogação nele

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top