簡體   English   中英

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
            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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM