【问题标题】:VBA: Put a space after or before a upppercase letter in a stringVBA:在字符串中的大写字母之后或之前放置一个空格
【发布时间】:2017-08-31 10:20:47
【问题描述】:

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

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

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

有人知道我该怎么做吗?

【问题讨论】:

标签: excel string vba function uppercase


【解决方案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

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

【讨论】:

  • 效果很好!感谢您的快速回复!
  • 很高兴收到你的来信。继续问。
  • Rajesh... 你能告诉我我应该在哪里调整代码以在大写字母之后添加空格吗?我自己分析了一下,这个功能对我来说还是太高级了!
  • xOut = xOut &amp; " " &amp; VBA.Mid(PValue, i, 1) 这一行加了一个空格,然后写上大写字母。如果您想在 之后添加空格,我不知道您为什么想要 J ohnW illiamsS mith,但该行将是 xOut = xOut &amp; VBA.Mid(PValue, i, 1) &amp; " "
  • 嘿垃圾,Gabriel 已经解决了这个问题。此代码将在每个字符后放置空格。 Function InsertSpaces(S As String) As String InsertSpaces = Trim(Replace(StrConv(S, vbUnicode), Chr(0), " ")) End Function
【解决方案2】:

除了@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之类的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    相关资源
    最近更新 更多