¿Cómo puedo determinar si el texto está en caracteres cirílicos?
-
03-07-2019 - |
Pregunta
Mi carpeta de correo no deseado se ha llenado de mensajes compuestos en lo que parece ser el alfabeto cirílico. Si el cuerpo del mensaje o el asunto del mensaje está en cirílico, quiero eliminarlo de forma permanente.
En mi pantalla veo caracteres cirílicos, pero cuando recorro los mensajes en VBA dentro de Outlook, el " Asunto " La propiedad del mensaje devuelve signos de interrogación.
¿Cómo puedo determinar si el asunto del mensaje está en caracteres cirílicos?
(Nota: he examinado la propiedad " InternetCodepage " generalmente es de Europa occidental.)
Solución
El tipo de datos String
en VB / VBA puede manejar caracteres Unicode, pero el IDE en sí tiene problemas para mostrarlos (por lo tanto, los signos de interrogación).
Escribí una función IsCyrillic
que podría ayudarte. La función toma un solo argumento String
y devuelve True
si la cadena contiene al menos un carácter cirílico. Probé este código con Outlook 2007 y parece funcionar bien. Para probarlo, me envié unos cuantos correos electrónicos con texto cirílico en la línea del asunto y verifiqué que mi código de prueba podía seleccionar correctamente esos correos electrónicos de entre todos los demás elementos de mi Bandeja de entrada.
Entonces, en realidad tengo dos fragmentos de código:
- El código que contiene la función
IsCyrillic
. Esto se puede copiar y pegar en un nuevo módulo VBA o añadido a el código que ya tienes. - La rutina
Test
que escribí (en Outlook VBA) para probar que el código realmente funciona. Demuestra cómo usar la funciónIsCyrillic
.
El 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
Ejemplo 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
Otros consejos
el " Asunto " propiedad del mensaje devuelve un montón de signos de interrogación.
Un problema clásico de codificación de cadenas. Parece que esa propiedad está devolviendo ASCII pero desea UTF-8 o Unicode.
Me parece que ya tiene una solución fácil, solo busque cualquier línea de asunto con (digamos) 5 signos de interrogación en ella