繁体   English   中英

从 VBA 中的文本中剥离特殊字符的问题

[英]Issues stripping special characters from text in VBA

我有一个 Excel 文件,它从 csv 中提取数据,对其进行一些操作,然后将其保存为一系列文本文件。

源数据中有一些特殊字符会出错,所以我添加了这个来去除它们

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?,â,€,™"

Function ReplaceSpecialCharacters(myString As String) As String

Dim newString As String
Dim char As Variant

newString = myString

For Each char In Split(SpecialCharacters, ",")
    newString = Replace(newString, char, "")
Next

ReplaceSpecialCharacters = newString

End Function

问题是这并没有抓住所有的人。 当我尝试处理以下文本时,它会跳过上面的代码并导致 Excel 出错。

Hero’s Village

我认为问题在于特殊字符未被 Excel 本身识别。 我只能通过将文本从 Excel 复制出来并将其粘贴到不同的 IDE 中来使文本看起来像上面那样。在 Excel 中显示为:

在工作簿中工作簿截图

在编辑区编辑栏截图

即时 window 即时窗口截图

基于此站点,它似乎在显示'字符时出现问题,但是如果它甚至无法在 VBA 本身中正确读取它,我该如何修复/过滤掉它?

Option Explicit
dim mystring as String
dim regex as new RegExp

Private Function rgclean(ByVal mystring As String) As String

'function that find and replace string if contains regex pattern
'returns str

    With regex

        .Global = True
        .Pattern = "[^ \w]" 'regex pattern will ignore spaces, word and number characters...

    End With

    rgclean = regex.Replace(mystring, "") '.. and replaces everything else with ""

End Function

尝试使用正则表达式。

确保启用正则表达式:工具 > 参考 > 复选框:“Microsoft VBScript 正则表达式 5.5”

将“mystring”字符串变量传递到 function (rgclean)。 function 将检查任何非空格、单词 [A-Za-z] 或数字 [0-9] 的内容,将它们替换为“”,然后返回字符串。

function 几乎会删除字符串中的所有符号。 不会排除任何数字、空格或单词。

这是相反的方法。 删除不包含在这组 62 中的所有字符:

ABCDEFGHIJKLMNOPQESTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

代码:

Const ValidCharacters As String = "ABCDEFGHIJKLMNOPQESTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

Function ReplaceSpecialCharacters(myString As String) As String
    
    Dim newString As String, L As Long, i As Long
    Dim char As Variant
    
    newString = myString
    L = Len(newString)
    
    For i = 1 To L
        char = Mid(newString, i, 1)
        If InStr(ValidCharacters, char) = 0 Then
            newString = Replace(newString, char, "@")
        End If
    Next i
    
    ReplaceSpecialCharacters = Replace(newString, "@", "")
    
End Function

在此处输入图像描述

笔记:

如果要保留字符,还可以将字符添加到字符串ValidCharacters中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM