![](/img/trans.png)
[英]Excel VBA - How can you find and replace single quotes on a 30k character string?
[英]VBA - Replace only a single whitespace (" ") in a string with a character
我有一个带有以下文本的字符串:
16/2730 99 16/2730 97 16/2730 81 16/2730 76 16/2730 103 16/2730 102 16/2730 101
我想用另一个字符“-”替换单个空格(“”)。 我想要的结果是:
16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101
关于如何用另一个字符替换单个空格,同时保留多个空格的任何建议?
除了 Tim Williams 在评论中的有效提示之外,另一种方法可能是以下方法(假设搜索数字、斜杠和单个空格" "
的序列可以识别为数字) :
""
的数组。例子
Sub Example()
Dim s As String
s = "16/2730 99 16/2730 97 16/2730 81 16/2730 76 16/2730 103 16/2730 102 16/2730 101"
Dim tmp As Variant
tmp = Split(s)
'Debug.Print Join(tmp, "|") ' optional display in immediate window
'Loop through splitted array elements
Dim i As Long
For i = 0 To UBound(tmp) - 1
If IsNumeric(tmp(i + 1)) Then ' if immediate right neighbour is numeric
tmp(i) = tmp(i) & "-" ' .. add a hyphen to the current element
ElseIf tmp(i) = "" Then ' if current element was a blank
tmp(i) = " " ' .. give it back its former value
End If
Next i
Debug.Print Join(tmp, "") ' put completed elements together again
End Sub
结果在 VB 编辑器的即时 window
16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.