VBA:在字符串中的大写字母之前或之后放置一个space

VBA: Put a space after or before a upppercase letter in a string

我有一系列代表客户姓名的文本,但每个 word/name 之间没有空格(例如:JohnWilliamsSmith)。但是可以区分单词,因为每个单词的第一个字母都是大写的。

所以我需要将这个客户字符串列表转换为它们的常规格式,每个单词之间有空格。所以我希望 JohnWilliamsSmith 成为 John WilliamsSmith。但是,我想不出立即实现这一目标的方法,而且我相信 Excel 公式的组合无法提供此结果。

因此,我认为唯一的解决办法是设置一个宏。它可能是一个 Function 用作公式,或者是模块中的代码来处理特定范围内的数据(假设列表在 Range ("A2: A100") 中)。

有人知道我该怎么做吗?

Function AddSpaces(PValue As String) As String

  Dim xOut As String
  xOut = VBA.Left(PValue, 1)

  For i = 2 To VBA.Len(PValue)
    xAsc = VBA.Asc(VBA.Mid(PValue, i, 1))

    If xAsc >= 65 And xAsc <= 90 Then
      xOut = xOut & " " & VBA.Mid(PValue, i, 1)
    Else
      xOut = xOut & VBA.Mid(PValue, i, 1)
    End If

  Next
  AddSpaces = xOut
End Function

注意:使用这个函数公式是=Addspace(A1)。

除了@Forty3 对你的问题的评论,关于如何在 VBA 中使用正则表达式的答案是 here

话虽如此,您正在寻找匹配 JohnWilliamsSmith 的正则表达式,即 ([A-Z])([a-z]+.*?)

Dim regex As New RegExp
Dim matches As MatchCollection
Dim match As match
Dim name As String


regex.Global = True
regex.Pattern = "([A-Z])([a-z]+.*?)"
name = "JohnWilliamsSmith"
Set matches = regex.Execute(name)

For Each match In matches
    name = Replace(name, match.Value, match.Value + " ")
Next match

name = Trim(name)

这给了我 John Williams Smith。当然,需要额外的编码来解释像 WillWilliamsWilliamson.

这样的情况