作为以下问题的后续行动:
How do I delete all characters after the first space in a cell?
我需要的是将这个功能从第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
答案 0 :(得分:4)
这种方法的有效性将依赖于每个单元的数据到达第一个空间的距离。我使用了99个字符的任意最大位置,这应该涵盖大多数情况。
使用Range.Replace method将每个空格转换为99个空格后,使用Range.TextToColumns method执行xlFixedWidth。通过分配正确的xlColumnDataType,只保留第一个“列”; TextToColumns会自动修剪多余的空格。
struct Node
{
int data;
Node * next;
Node * prev;
Node() : next(nullptr), prev(nullptr) {} // <<<<<<<<<<<<<<<<<<<
};
如果您开始对几百个单元格执行此操作,TextToColumns优于循环遍历每个单元格并单独解析该值的优势将很快变得明显。
答案 1 :(得分:3)
考虑:
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
注:的
如果单元格不包含空格,则保持不变。
答案 2 :(得分:2)
请尝试以下代码:
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
End Sub
如果您使用的是Excel 2003或更早版本,请使用VI2而不是XFD2
答案 3 :(得分:2)
见下文
除了TMP减少
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