gpt4 book ai didi

excel - 在 Excel 中去除前导/尾随空格和逗号

转载 作者:行者123 更新时间:2023-12-04 06:01:38 25 4
gpt4 key购买 nike

这似乎是一个如此简单的要求,我觉得我错过了一些明显的东西。

我有一个 Excel 电子表格,其中包含“脏”文本数据,其中包含文本和不需要的前导和尾随、空格、逗号和换行符。我想修剪对所有这些字符的这些单元格的引用。

注意:我不想替换所有这些字符,因为它们合法地出现在单元格文本中 - 只是在单元格文本(即值)的开头或结尾时,我想将它们修剪掉。

文本数据由人和学校的名称组成,用于清理和导入 CRM。

那么,是否有内置功能,还是我需要编写一个?我被 PHP 中的字符串过滤函数的数量宠坏了 ;-)

最佳答案

这非常适合正则表达式

下面的代码adapted from this article使用这个正则表达式"[,\s]*(.+?)[,\s]*$"删除任何前导和/或尾随空格/逗号,同时将文本正文中的任何此类字符保持不变

它将就地替换您现有的数据

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), "$1")
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, "$1")
End If
Next rngArea

'cleanup the Application settings
With Application
.ScreenUpdating = True
.Calculation = lngCalc
.EnableEvents = True
End With

Set objReg = Nothing
End Sub

关于excel - 在 Excel 中去除前导/尾随空格和逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8844588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com