如何摆脱excel中的前导空格?
我有很多行有这个问题。
答案 0 :(得分:10)
在您的空白删除请求中请注意:
TRIM
仅删除字符32,即标准空格。 CLEAN
将删除非打印空格,例如回车符(字符13)和换行符(字符10)CLEAN
不处理不间断的空格(字符160),这是处理来自网络数据的常见问题,因此您需要SUBSTITUTE
函数您可以使用整个单元格中的公式执行此操作,也可以使用vba
更轻松地(并使用前导空格定位)使用Formula,您可以结合使用这三个公式来清理整个单元格
=TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))
。请参阅Ron de Bruins的撰写here
下面的VBA将使用数组和正则表达式有效地替换您的数据,而无需任何工作列和复制和粘贴。使用说明包含在下面的代码中。此代码仅适用于字符串的前导部分,与公式选项
不同 Sub KillLeadingSpaces()
'Press Alt + F11 to open the Visual Basic Editor (VBE)
'From the Menu, choose Insert-Module.
'Paste the code into the right-hand code window.
'Press Alt + F11 to close the VBE
'In Xl2003 Goto Tools ....Macro .... Macros and double-click KillLeadingSpaces
'In Xl2007/10 Goto Developer .. Macros and double-click KillLeadingSpaces
Dim rng1 As Range
Dim rngArea As Range
Dim lngRow As Long
Dim lngCol As Long
Dim lngCalc As Long
Dim objReg As Object
Dim X()
On Error Resume Next
Set rng1 = Application.InputBox("Select range for the replacement of leading zeros", "User select", Selection.Address, , , , , 8)
If rng1 Is Nothing Then Exit Sub
On Error GoTo 0
'See Patrick Matthews excellent article on using Regular Expressions with VBA
Set objReg = CreateObject("vbscript.regexp")
objReg.Pattern = "^[\s|\xA0]+"
'Speed up the code by turning off screenupdating and setting calculation to manual
'Disable any code events that may occur when writing to cells
With Application
lngCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
End With
'Test each area in the user selected range
'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on
For Each rngArea In rng1.Areas
'The most common outcome is used for the True outcome to optimise code speed
If rngArea.Cells.Count > 1 Then
'If there is more than once cell then set the variant array to the dimensions of the range area
'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks
X = rngArea.Value2
For lngRow = 1 To rngArea.Rows.Count
For lngCol = 1 To rngArea.Columns.Count
'replace the leading zeroes
X(lngRow, lngCol) = objReg.Replace(X(lngRow, lngCol), vbNullString)
Next lngCol
Next lngRow
'Dump the updated array sans leading whitepace back over the initial range
rngArea.Value2 = X
Else
'caters for a single cell range area. No variant array required
rngArea.Value = objReg.Replace(rngArea.Value, vbNullString)
End If
Next rngArea
'cleanup the Application settings
With Application
.ScreenUpdating = True
.Calculation = lngCalc
.EnableEvents = True
End With
Set objReg = Nothing
End Sub
答案 1 :(得分:5)
假设您想要删除A列中的空格。
=TRIM(A1)
。 答案 2 :(得分:2)
您可以使用内置的TRIM
功能吗?它从传入其中的文本的开头和结尾删除空格:
=TRIM(A1)
此公式将为您提供单元格A1中没有前导或尾随空格的文本。
要使用公式,您可以在原始列旁边插入一列。然后在第一个(顶部)空单元格中输入公式,将原始列的第一个(顶部)单元格的单元格坐标替换为“A1”,然后按Enter键。然后,您可以抓住单元格的右下角(光标将更改为“+”符号),然后将该框向下拖动到新列中的最后一个单元格,以重复列中所有行的公式。