VBA:在字符串

时间:2017-04-05 16:59:08

标签: excel string vba function uppercase

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

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

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

有谁知道我该怎么做?

2 个答案:

答案 0 :(得分:2)

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)。

答案 1 :(得分:1)

除了@ 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等案例。