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

╄→гoц情女王★ 提交于 2019-12-11 04:29:32

问题


I have a sequence of texts that represent customers names, but they do not have spaces between each word/name (for example: JohnWilliamsSmith). However the words can be differentiated because the first letter of each word is uppercase.

So I need to transpose this list of customers strings to their regular format, with spaces between each word. So I want JohnWilliamsSmith to become John Williams Smith. However, I couldn't think of an immediate way to achieve this, and I believe that no combination of Excel formulas can offer this result.

Thus, I think the only solution would be to set up a Macro. It might be a Function to be used as a formula, or a code in module to work the data in a certain range (imagine that the list is in Range ("A2: A100")).

Does anyone have any idea how I can do this?


回答1:


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

NB: Use this Function formula is =Addspace(A1).




回答2:


In addition to @Forty3's comment to your question, the answer on how to use Regular Expressions in VBA is here.

With that being said you are then looking for the regular expression to match John, Williams, Smith which is ([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)

This gives me John Williams Smith. Of course, additional coding will be needed to account for cases like WillWilliamsWilliamson.



来源:https://stackoverflow.com/questions/43237341/vba-put-a-space-after-or-before-a-upppercase-letter-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!