vba 在 Excel 中去除前导/尾随空格和逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8844588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Strip leading/trailing spaces and commas in Excel
提问by Jason
This seems like such a simple requirement, that I feel like I am missing something obvious.
这似乎是一个如此简单的要求,我觉得我错过了一些明显的东西。
I have an Excel spreadsheet with "dirty" text data in, containing text and unwanted leading and trailing, spaces, commas and newlines. I would like to TRIM references to these cells of all those characters.
我有一个带有“脏”文本数据的 Excel 电子表格,其中包含文本和不需要的前导和尾随、空格、逗号和换行符。我想修剪对所有这些字符的这些单元格的引用。
Note: I don't want to replace all those characters, since they legitimately appear within the cell text - it is just when at the start or end of the cell text (i.e. value) that I want to trim them off.
注意:我不想替换所有这些字符,因为它们合法地出现在单元格文本中 - 只是在单元格文本(即值)的开头或结尾时,我想将它们修剪掉。
The text data consists of names of people and schools, for cleaning and importing into a CRM.
文本数据由人和学校的名称组成,用于清理和导入 CRM。
So, is there a function built in, or do I need to write one? I feel spoiled by the number of string filtering functions in PHP ;-)
那么,是否有内置函数,或者我需要编写一个函数吗?我被 PHP 中的字符串过滤函数的数量宠坏了 ;-)
回答by brettdj
This is well suited to a regexp
这非常适合正则表达式
The code below adapted from this articleuses this regexp"[,\s]*(.+?)[,\s]*$"
to remove any leading and/or trailing whitespaces/commas while leaving any such characters within the text body intact
下面改编自本文的代码使用此正则表达式"[,\s]*(.+?)[,\s]*$"
来删除任何前导和/或尾随空格/逗号,同时在文本正文中保留任何此类字符
It will replace your existing data in-situ
它将就地替换您现有的数据
Sub RemoveDirt()
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.MultiLine = True
objReg.Pattern = "[,\s]*(.+?)[,\s]*$"
'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), "")
Next lngCol
Next lngRow
'Dump the updated array sans dirt 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, "")
End If
Next rngArea
'cleanup the Application settings
With Application
.ScreenUpdating = True
.Calculation = lngCalc
.EnableEvents = True
End With
Set objReg = Nothing
End Sub
回答by Jason
I have found this code, which I pasted in as a module into my spreadsheet:
我找到了这段代码,我将其作为模块粘贴到我的电子表格中:
Option Explicit
Function ReReplace(ReplaceIn, _
ReplaceWhat As String, ReplaceWith As String, Optional IgnoreCase As Boolean = False)
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.IgnoreCase = IgnoreCase
RE.Pattern = ReplaceWhat
RE.Global = True
ReReplace = RE.Replace(ReplaceIn, ReplaceWith)
End Function
This provides a replace function that supports REs (why doesn't Excel do that itself? It has only been around since 1987 - I had it on my Atari ST, note that you can add more than ten cells before it crashed!). This cell function is able to do the trimming I need:
这提供了一个支持 RE 的替换功能(为什么 Excel 本身不这样做?它自 1987 年以来才出现 - 我在我的 Atari ST 上有它,注意你可以在它崩溃之前添加十个以上的单元格!)。这个单元格功能能够完成我需要的修剪:
=ReReplace('source worksheet'!cell_reference, "^[\s,]+|[\s,]+$", "")
This works beautifully.
这很好用。
(Note: this answer moved from the question text, where it really should not have been.)
(注意:这个答案从问题文本中移出,它真的不应该出现在那里。)
回答by Rohan Khude
I tried this using two steps
我用两个步骤试过这个
- By removing spaces
- By removing comma
- 通过删除空格
- 通过删除逗号
For removing leading and trailing spaces
用于删除前导和尾随空格
Use direct function TRIM(A1)
使用直接函数 TRIM(A1)
For removing leading and trailing comma
用于删除前导和尾随逗号
=MID(A1,IF(FIND(",",A1)=1,2,1),IF(RIGHT(A1)=",",LEN(A1)-2,LEN(A1)))
or
或者
=SUBSTITUTE(TRIM(SUBSTITUTE(A1,","," "))," ",",")
回答by AT_
Recursive function to remove comma and trailing spaces. Pure VBA..
删除逗号和尾随空格的递归函数。纯VBA..
Function removetrailcomma(txt As String) As String
If Right(txt, 1) = " " Or Right(txt, 1) = "," Then
removetrailcomma = removetrailcomma(Left(txt, Len(txt) - 1))
Else
removetrailcomma = txt
End If
End Function