【发布时间】:2013-03-30 21:26:28
【问题描述】:
我需要从字符串中删除除 Excel 中的句点和空格之外的所有非字母数字字符。使用 VBA 而不是纯 excel 函数的解决方案就可以了。
【问题讨论】:
-
看到这个问题,除了句号/空格部分。你的模式就像 [A-Z,a-z,0-9,\.,\s] stackoverflow.com/questions/10789948/…
我需要从字符串中删除除 Excel 中的句点和空格之外的所有非字母数字字符。使用 VBA 而不是纯 excel 函数的解决方案就可以了。
【问题讨论】:
将此函数插入到 Visual Basic 编辑器的新模块中:
Function AlphaNumericOnly(strSource As String) As String
Dim i As Integer
Dim strResult As String
For i = 1 To Len(strSource)
Select Case Asc(Mid(strSource, i, 1))
Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space
strResult = strResult & Mid(strSource, i, 1)
End Select
Next
AlphaNumericOnly = strResult
End Function
现在您可以将其用作用户定义函数,即如果您的数据在单元格 A1 中,则将此公式放在空单元格 =AlphaNumericOnly(A1) 中。
如果您想直接转换大范围,即在不离开源代码的情况下替换所有非字母数字字符,您可以使用另一个 VBA 例程来执行此操作:
Sub CleanAll()
Dim rng As Range
For Each rng In Sheets("Sheet1").Range("A1:K1500").Cells 'adjust sheetname and range accordingly
rng.Value = AlphaNumericOnly(rng.Value)
Next
End Sub
只需将此 sub 放在同一个模块中并执行它。但请注意,这将替换该范围内的所有公式。
【讨论】:
? Asc("A") 来获取 ASCII 码...
这里'使用模式匹配从字符串中删除“你想要的任何字符”的另一种方法。
下面的示例删除所有除了字母、数字、空格和句点 ([A-Z.a-z 0-9])
为了提高效率,它还在字符串和字节数组之间使用了 VBA 的 seamless conversion:
cleanString函数:Function cleanString(str As String) As String Dim ch, bytes() As Byte: bytes = str For Each ch In bytes If Chr(ch) Like "[A-Z.a-z 0-9]" Then cleanString = cleanString & Chr(ch) Next ch End Function
Like 运算符创建模式的更多信息,请参阅:
【讨论】:
For i =... 与 For each...
我一直在寻找一种比我想出的更优雅的解决方案。我打算使用上面的 ashleedawg 的代码,因为它肯定比我的代码更整洁。具有讽刺意味的是,我的跑得快了 30%。如果速度很重要(假设您有几百万要做),试试这个:
Public Function AlphaNumeric(str As String) As String
Dim i As Integer
For i = 1 To Len(str)
If InStr(1, "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. ", Mid(str, i, 1)) Then AlphaNumeric = AlphaNumeric & Mid(str, i, 1)
Next
End Function
VBA 的每一个角落都有惊喜。我从来没有想过这会更快......
【讨论】:
我编写了以下代码,就我测试它而言,它是有效的,它由两个函数组成。第一个检查字符串是否是字母数字,第二个进行替换(它也删除空格)
Public Function Isalphanumeric(cadena As String) As Boolean
Select Case Asc(UCase(cadena))
Case 65 To 90 'letras
Isalphanumeric = True
Case 48 To 57 'numeros
Isalphanumeric = True
Case Else
Isalphanumeric = False
End Select
End Function
这里是删除功能
Function RemoveSymbols_Enhanced(InputString As String) As String
Dim InputString As String
Dim CharactersArray()
Dim i, arrayindex, longitud As Integer
Dim item As Variant
i = 1
arrayindex = 0
longitud = Len(InputString)
'We create an array with non alphanumeric characters
For i = 1 To longitud
If Isalphanumeric(Mid(InputString, i, 1)) = False Then
ReDim Preserve CharactersArray(arrayindex)
CharactersArray(arrayindex) = Mid(InputString, i, 1)
arrayindex = arrayindex + 1
End If
Next
'For each non alphanumeric character we do a replace
For Each item In CharactersArray
item = CStr(item)
InputString = Replace(InputString, item, "")
Next
End Function
【讨论】: