VBA - 仅将字符串中的一个空格 (" ") 替换为一个字符

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
            ' .. give back the former blank values (<~~ Edited ~~>)
            tmp(i) = IIf(IsNumeric(Right(tmp(i + 1), 1)), "  ", " ")
        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