删除特殊字符VBA Excel

问题描述 投票:0回答:5

我正在使用 VBA 阅读一些标题,然后将该信息复制到 PowerPoint 演示文稿中。

问题是标题有特殊字符,但我正在处理的图像文件没有。

标题构成将 JPEG 加载到图片容器中的路径的一部分,例如

P k.jpg
,但标题称为
p.k

我希望能够忽略标题中的特殊字符,只让它看到一个空格,这样它就会选择正确的 JPG 文件。

我该怎么做?

vba excel excel-2010
5个回答
49
投票

您认为什么是“特殊”字符,只是简单的标点符号?您应该能够使用

Replace
功能:
Replace("p.k","."," ")

Sub Test()
Dim myString as String
Dim newString as String

myString = "p.k"

newString = replace(myString, ".", " ")

MsgBox newString

End Sub

如果您有多个角色,您可以在自定义函数或一系列简单的

Replace
函数等中执行此操作。

  Sub Test()
Dim myString as String
Dim newString as String

myString = "!p.k"

newString = Replace(Replace(myString, ".", " "), "!", " ")

'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")

MsgBox newString

End Sub

如果您有很多潜在的特殊字符(例如非英语重音的 ascii?),您可以对数组执行自定义函数或迭代。

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?"  'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
    newString = Replace(newString, char, " ")
Next
End Sub

18
投票

如果您不仅要排除特殊字符列表,而且要排除all非字母或数字的字符,我建议您使用 char 类型比较方法。

对于字符串中的每个字符,我将检查unicode字符是否在“A”和“Z”之间、“a”和“z”之间或“0”和“9”之间。这是vba代码:

Function cleanString(text As String) As String
    Dim output As String
    Dim c 'since char type does not exist in vba, we have to use variant type.
    For i = 1 To Len(text)
        c = Mid(text, i, 1) 'Select the character at the i position
        If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
            output = output & c 'add the character to your output.
        Else
            output = output & " " 'add the replacement character (space) to your output
        End If
    Next
    cleanString = output
End Function

如果您想进一步自定义此功能,Unicode 字符维基百科列表 是一个很好的快速入门。

该解决方案的优点是即使用户找到引入新特殊字符的方法也能正常工作。它也比比较两个列表更快。


10
投票

这是删除特殊字符的方法。

我只是应用了正则表达式

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

2
投票

这就是我使用的,基于这个link

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

用途:

=StripAccentb(B2) ' cell address

工作表中所有单元格的子版本:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

0
投票

根据 Ferroao 的长字符列表,我正在使用此功能:

Function replaceSpecialCharacters(str As String)
Dim badCharacters, goodCharacters As Variant
Dim i As Integer
badCharacters = Array("Š", "Ž", "š", "ž", "Ÿ", "À", "Á", "Â", "Ã", "Ä", "Å", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ù", "Ú", "Û", "Ü", "Ý", "à", "á", "â", "ã", "ä", "å", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ù", "ú", "û", "ü", "ý", "ÿ")
goodCharacters = Array("S", "Z", "s", "z", "Y", "A", "A", "A", "A", "A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I", "D", "N", "O", "O", "O", "O", "O", "U", "U", "U", "U", "Y", "a", "a", "a", "a", "a", "a", "c", "e", "e", "e", "e", "I", "I", "I", "I", "d", "n", "o", "o", "o", "o", "o", "u", "u", "u", "u", "y", "y")

For i = 0 To UBound(badCharacters)
  str = Replace(str, badCharacters(i), goodCharacters(i))
Next i

replaceSpecialCharacters = str

End Function

从其他地方调用该函数

Debug.Print replaceSpecialCharacters("žÃÌý")

或者

BadString = "žÃÌý"
GoodString =  replaceSpecialCharacters(BadString)

旁注:
该方法是将特殊字符替换为最接近的匹配项,例如将 ž 替换为 z。

PS:
OP提到了一个特殊字符“.”,它也可以包含在两个数组中,因此“.”例如:替换为“”。

© www.soinside.com 2019 - 2024. All rights reserved.