VBA:在字符串中的上写字母之后或之前放置一个空格



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

因此,我需要将此客户字符串列表转换为常规格式,每个单词之间都有空格。所以我希望约翰·威廉姆斯·史密斯成为约翰·威廉姆斯·史密斯但是,我想不出立即实现这一目标的方法,我相信没有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

注意:使用此函数公式是 = 添加空间(A1(。

除了@Forty3对您的问题的评论外,有关如何在 VBA 中使用正则表达式的答案在这里。

话虽如此,您正在寻找正则表达式来匹配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 .

相关内容

最新更新