Excel - 查找和;替换部分字符串,但在同一个单元格?

时间:2013-08-01 19:28:33

标签: excel vba excel-vba

我有

Column A

Red-US
Blue-INT
Purple-INT
White-US-CA

尝试删除-us, int, ca, etc.

所以它只是Red, Blue, Purple, etc.

不能使用修剪或替代公式,因为我希望它直接在A列(替换)中更改

谢谢!

2 个答案:

答案 0 :(得分:1)

如果“ - ”是一致的分隔符,那么它应该非常简单。

以下是您可以使用的一些命令:

Strings and Manipulations

修改:添加了简单代码

Sub textuptodash()
    i = 1 'start on row 1
    Do While Not IsEmpty(Cells(i, 1)) 'do until cell is empty
        If Not InStr(1, Cells(i, 1), "-") = 0 Then 'if dash in cell
            Cells(i, 1) = Left(Cells(i, 1), InStr(1, Cells(i, 1), "-") - 1) 'change cell contents
        End If
        i = i + 1 'increment row
    Loop
End Sub

答案 1 :(得分:0)

尝试使用Split,如下所示:

Sub MySplit()

    Dim rngMyRange As Range, rngCell As Range
    Dim strTemp() As String, strDel As String, strTest As String
    Dim lngCnt As Long
    Set rngMyRange = Range("A1:A4")

    For Each rngCell In rngMyRange
        ' Split the test based on the delimiter
        ' Store entries in a vector of strings
        strTemp = Split(rngCell.Text, "-")
        ' Reset cell value and intermmediate delimiter
        rngCell.Value = vbNullString
        strDel = vbNullString
        ' Scan all entries. store all of them but not the last -* part
        For lngCnt = LBound(strTemp) To UBound(strTemp) - 1
            rngCell = rngCell & strDel & strTemp(lngCnt)
            ' If we enter the loop again we will need to apend a "-"
            strDel = "-"
        Next lngCnt
    Next rngCell
End Sub

输出:

Red
Blue
Purple
White-US

您希望如何拆分最后一个条目并不完全清楚:假设您只想删除最后一个“ - *”位。要仅保留第一部分,请注释掉For lngCnt循环。

我希望这有帮助!