VBA:在一个string中的upppercase字母之后或之前放置一个空格

我有一系列代表顾客姓名的文字,但每个单词/名称之间没有空格(例如: JohnWilliamsSmith )。 但是,由于每个单词的首字母都是大写,所以可以区分单词。

所以我需要将这个客户string列表转换为它们的常规格式,每个单词之间有空格。 所以我想让约翰·威廉斯·史密斯成为约翰·威廉姆斯·史密斯 。 但是,我想不出一个立竿见影的办法来实现这一点,我相信,Excel公式的组合可以提供这个结果。

因此,我认为唯一的解决办法是build立一个macros。 这可能是一个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中使用正则expression式的答案在这里 。

有人说,你正在寻找正则expression式来匹配JohnWilliamsSmith ([AZ])([az]+.*?)

 Dim regex As New RegExp Dim matches As MatchCollection Dim match As match Dim name As String regex.Global = True regex.Pattern = "([AZ])([az]+.*?)" 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这样的WillWilliamsWilliamson