我想使用VBA刪除字符串中不必要的空格,但修剪功能似乎不適用於我。在這個假設的例子中,我想刪除「結束」和「時間」之間的額外空間。Excel VBA - 無法使用修剪和類似功能刪除單詞之間的多餘空格
Public Sub RemoveSpaces()
Dim s As String: s = "START TIME: N/A END TIME: N/A "
s = Trim(s)
Debug.Print s
End Sub
我想使用VBA刪除字符串中不必要的空格,但修剪功能似乎不適用於我。在這個假設的例子中,我想刪除「結束」和「時間」之間的額外空間。Excel VBA - 無法使用修剪和類似功能刪除單詞之間的多餘空格
Public Sub RemoveSpaces()
Dim s As String: s = "START TIME: N/A END TIME: N/A "
s = Trim(s)
Debug.Print s
End Sub
簡單(也可能是表現最好的)這樣做是與方式正則表達式:
'Requires reference to Microsoft VBScript Regular expressions
Private Function RemoveExtraSpace(inVal As String) As String
With New RegExp
.Pattern = "\s+"
.Global = True
RemoveExtraSpace = .Replace(inVal, " ")
End With
End Function
Sub Example()
Dim s As String
s = "START TIME: N/A END TIME: N/A "
Debug.Print RemoveExtraSpace(s)
End Sub
後期綁定版本:
Private Function RemoveExtraSpace(inVal As String) As String
With CreateObject("VBScript.RegExp")
.Pattern = "\s+"
.Global = True
RemoveExtraSpace = .Replace(inVal, " ")
End With
End Function
編輯:如果你想換行保持,換着花樣給.Pattern = "[ ]+"
(括號內爲可讀性)
With New RegExp
.Pattern = "\s+"
.Global = True
.MultiLine = True
RemoveExtraSpace = .Replace(inVal, " ")
End With
:如果每個評論需要多,只是增加了額外的參數。
關閉我的頭頂,我會使用split
功能,然後加入碎片重新走到一起。
Dim s As String: s = "START TIME: N/A END TIME: N/A "
sParts = Split(s, " ")
s_wo_xtra_space = ""
for i = lbound(sParts) to ubound(sParts)
if sParts(i) <> "" then
s_wo_xtra_space = s_wo_xtra_space & sParts(i) & " "
end if
next i
s_wo_xtra_space = trim(s_wo_xtra_space)
這假設你仍然希望單詞之間有一個空格。
通過分割空間,您將獲得11個項目。如果您沒有在循環中放置邏輯來跳過空項目,最終結果將如輸入 –
優秀點一樣。我會解決的。 –
您可以使用分裂()通過對空間的分割,然後循環和跳過合成陣列中的所有空項目:
Public Sub RemoveSpaces()
Dim s As String: s = "START TIME: N/A END TIME: N/A "
Dim str() As String
Dim str1
str = Split(s)
s = ""
For Each str1 In str
If str1 <> "" Then
s = s & str1 & " "
End If
Next str1
s = Trim(s)
Debug.Print s
End Sub
也許app.Worksheetfunction.Trim?
Public Sub RemoveSpaces()
Dim s As String: s = "START TIME: N/A END TIME: N/A "
s = Application.WorksheetFunction.Trim(s)
Debug.Print s
End Sub
哦,我看@ @萊克西奧爾森是第一個這樣的人。
do until instr(s, " ") = 0
s = replace(s, " ", " ")
loop
或者,如果你想要做一個UDF,你可以做這樣的事情,然後刪除雙倍的空間,你可以做S = RmvDblSpc(S)
Function RmvDblSpc(What As String) As String
Do Until InStr(What, " ") = 0
What = Replace(What, " ", " ")
Loop
RmvDblSpc = What
End Function
如何循環幾次更換''「'用''」''(雙空間單空格)然後修剪? –
我正在尋找更清潔的解決方案,但如果找不到其他任何東西,我會採取措施。我正在處理大段文字 – BDillan
您是否嘗試過'Application.WorksheetFunction.Trim'函數?看到這裏:http://stackoverflow.com/questions/7400293/vba-unable-to-remove-the-spaces –