2014-03-27 157 views
0

我正在尋找一種在文本數值和數值之間放置空格的方法,但有一個問題。有時文本也可能以數字開頭,我不希望這包含空格。例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 

哪裏柱A是值和Col B包含公式的空間增加值是上校A.

幾件事情要注意這裏:

  1. 的空格總是添加到文本結束後的第一個數字。

  2. 如果該值與一個數字,一個應該被忽略,並且再次在文本之後的第一個數字開始應該添加到它

  3. 的空間,如果已經有一個空間,另一個不應該添加。

  4. 文本的長度號碼前變化

  5. 沒有總是一個:值之間的第一個數字

後,我處理的數據集是約1000項所以速度不是必要的,只需要適用於所有情況的東西,因爲我不想通過許多條目並添加空間。

編輯最終解決方案感謝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

+0

如果值後所需的空間:「名稱」和「瓦爾」,我們可以利用查找和替換? – zx8754

+0

因此,列A是你*擁有*和列B是你*想要*。是對的嗎? – PowerUser

回答

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

+0

完美的作品。這是OP想要的東西:) –

+0

你好,謝謝你的回答,我會試試看。你能否請教如何在谷歌電子表格中使用宏?或者我是否需要將結果傳輸到Excel然後返回到Google電子表格? – DMCApps

+0

我也想知道如何在Google文檔中運行宏! –

相關問題