Excel - 在数字和单词之间添加空格

时间:2014-03-27 14:30:10

标签: excel

我正在寻找一种在文本值和数值之间放置空格的方法,但是有一个障碍。有时文本也可能以数字开头,我不希望它包含空格。例如

Col A                 Col B
Name1:3-2             Name 1:3-2
Name6:5,4             Name 6:5,4
1 Val55:12-4          1 Val 55:12-4
2 Val 22:43           2 Val 22:43
Name10                Name 10

其中Col A是值,Col B包含将值添加到值的公式是Col A.

这里有几点需要注意:

  1. 在文本结束后,空格始终仅添加到第一个数字。

  2. 如果值以一个应该被忽略的数字开头,并且文本后面的第一个数字应该添加空格

  3. 如果已经有空格,则不应添加其他空格。

  4. 数字变化前的文本长度

  5. 第一个数字

  6. 之后的值之间并不总是:

    我正在使用的数据集大约有1,000个条目,所以速度不是必需的,只需要适用于所有情况的东西,因为我不想通过那么多条目并添加空格。

    编辑最终解决方案感谢Gary的学生在下面:

    ' Function Assumes that there are atleast 2 characters in front of the expected space
    ' Function Assumes that there are no numbers within the text that will cause an early splitting of characters
    Public Function SpacedOut(sIn As String) As String
        Dim L As Long, i As Long, Done As Boolean
        Dim sOut As String
        L = Len(sIn)
        Done = False
        sOut = Left(sIn, 1)
        ' Skips the first possible number if it is there if not, we are safe to start at 2
        ' Since there will always be more than one character prior to the expected first number
        For i = 2 To L
            ' Check for a number without a space before it
            If Mid(sIn, i - 1, 1) <> " " And Mid(sIn, i, 1) Like "[0-9]" And Not Done Then
                Done = True
                sOut = sOut & " " & Mid(sIn, i, 1)
            ' Check for a space with a number after it and continue on if this is found
            ElseIf Mid(sIn, i - 1, 1) = " " And Mid(sIn, i, 1) Like "[0-9]" And Not Done Then
                Done = True
                sOut = sOut & Mid(sIn, i, 1)
            ' Append next character
            Else
                sOut = sOut & Mid(sIn, i, 1)
            End If
        Next i
        SpacedOut = sOut
    End Function
    

    谢谢, DMAN

1 个答案:

答案 0 :(得分:3)

试试这个小 UDF

Public Function SpacedOut(sIn As String) As String
    Dim L As Long, i As Long, Done As Boolean
    Dim sOut As String
    L = Len(sIn)
    Done = False
    sOut = Left(sIn, 1)
    For i = 2 To L
        If Mid(sIn, i - 1, 1) Like "[a-zA-Z]" And Mid(sIn, i, 1) Like "[0-9]" And Not Done Then
            Done = True
            sOut = sOut & " " & Mid(sIn, i, 1)
        Else
            sOut = sOut & Mid(sIn, i, 1)
        End If
    Next i
    SpacedOut = sOut
End Function

修改#1:

以下是我的VBE屏幕的快照,模块点亮:

SNAP