pix*_*xie 10 excel vba excel-vba excel-2010
我正在使用VBA读取一些TITLES,然后将该信息复制到powerpoint演示文稿中.
我的问题是,TITLES有特殊的字符,但我也在处理的图像文件没有.
TITLE构成了将JPEG加载到图片容器中的路径的一部分.例如"P k.jpg",但标题称为"pk".
我希望能够忽略TITLE中的特殊字符,只是让它看到一个空格,以便它选择正确的JPG文件.
那可能吗?
谢谢!
Dav*_*ens 34
你认为"特殊"字符是什么,只是简单的标点符号?你应该能够使用这个Replace功能:Replace("p.k","."," ").
Sub Test()
Dim myString as String
Dim newString as String
myString = "p.k"
newString = replace(myString, ".", " ")
MsgBox newString
End Sub
Run Code Online (Sandbox Code Playgroud)
如果您有多个字符,可以在自定义函数或简单链接的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
Run Code Online (Sandbox Code Playgroud)
如果您有很多潜在的特殊字符(例如非英语重音的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
Run Code Online (Sandbox Code Playgroud)
如果您不仅要排除特殊字符列表,而且要排除所有非字母或数字的字符,我建议您使用字符类型比较方法.
对于String中的每个字符,我将检查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
Run Code Online (Sandbox Code Playgroud)
如果您想要更多地自定义此功能,维基百科的Unicode characers列表是一个很好的快速入门.
即使用户找到引入新特殊字符的方法,该解决方案也具有功能上的优点.它也比将两个列表比较快.
这是删除特殊字符的方法。
我只是应用了正则表达式
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123610 次 |
| 最近记录: |