删除单元格中第一个空格之后的所有字符

作为以下问题的后续处理:

如何删除单元格中第一个空格之后的所有字符?

我需要的是将这个函数从行M2应用到列M末尾的最后一个条目。如果我有这个代码,我该怎么做:

Sub TMP() Dim strCodeWithDesc As String Dim strCodeOnly As String strCodeWithDesc = Range("M2").Value strCodeOnly = Left(strCodeWithDesc, InStr(strCodeWithDesc, " ") - 1) Range("M2").Value = strCodeOnly End Sub 

这种方法的有效性将取决于第一个空间将被发现的每个单元格的数据量。 我已经使用了99个字符的任意最大位置,它应该覆盖大多数情况。

使用Range.Replace方法将每个空格转换为99个空格后,使用xlFixedWidth执行Range.TextToColumns方法 。 只有第一个“列”通过分配正确的xlColumnDataType来保留; TextToColumns自动修剪多余的空间。

 Sub keepFirstWord() With Worksheets("Sheet2") With .Range(.Cells(2, 13), .Cells(Rows.Count, 13).End(xlUp)) .Replace What:=Chr(32), Replacement:=Space(99), LookAt:=xlPart .TextToColumns Destination:=Range("M2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(99, 9)) End With End With End Sub 

如果您开始在几百个单元格上执行此操作,那么TextToColumns优于循环遍历每个单元格的优点,而单独parsing该值将很快变得明显。

keep_first_word_before
keepFirstWord()之前的示例数据

keep_first_word_after
keepFirstWord()之后的示例数据

考虑:

 Sub Paolo() Dim r As Range For Each r In Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).Cells.SpecialCells(xlCellTypeConstants) r.Value = Split(r.Value, " ")(0) Next r End Sub 

注意:

如果单元格不包含空格,则保持不变。

见下文

除了TMP减less之外

 Option Explicit Sub main() Dim ws As Worksheet Dim lastRow As Long, i As Long Set ws = ThisWorkbook.Worksheets("CodeAndDesc") '<== set it as per your needs With ws lastRow = .Cells(.Rows.Count, 13).End(xlUp).row For i = 2 To lastRow Call TMP(.Cells(i, 13)) Next i End With End Sub Sub TMP(rng As Range) With rng .Value = Left(.Value, InStr(.Value, " ") - 1) End With End Sub 

尝试下面的代码:

Sub TMP()

 Dim strCodeWithDesc As String Dim strCodeOnly As String Dim R as range For Each R in Range(Range("M2"), Range("XFD2").end(xltoleft)) strCodeWithDesc = R.Value strCodeOnly = Left(strCodeWithDesc, InStr(1,strCodeWithDesc, " ",vbTextCompare) - 1) R.Value = strCodeOnly Next R 

结束小组

如果您使用Excel 2003或更早版本,请使用VI2而不是XFD2