gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:30:23 29 4
gpt4 key购买 nike

作为以下问题的后续:

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

最佳答案

此方法的有效性将取决于第一个空格在每个单元格的数据中有多远。我使用了 99 个字符的任意最大位置,这应该涵盖大多数情况。

使用 Range.Replace method 后要将每个空格转换为 99 个空格,a Range.TextToColumns method执行 xlFixedWidth 。通过分配正确的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 的优势过度循环每个 cellnd 单独解析值很快就会变得明显。

         keep_first_word_before
                 keepFirstWord()之前的示例数据

         keep_first_word_after
                 keepFirstWord()之后的示例数据

关于vba - 删除整个列中单元格中第一个空格之后的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969634/

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