Excel-在找到数字后跟字母字符的组合后修剪文本

时间:2018-12-17 10:18:31

标签: excel excel-formula excel-2010

如何修剪下面的包含字母数字字符的文本,并提供说明。

示例文字:BACA-AA01A-withsomediscription,               BACA-AA01Bwithsomediscription

每个代码都以数字和字母顺序结尾。 “ BACA-AA01A”,“ BACA-AA01B”。因此,在找到数字和字母组合后,我需要一个极好的公式来修饰我的文字。

2 个答案:

答案 0 :(得分:1)

这是一个功能-将其粘贴到模块页面中,您可以在电子表格中使用该功能

Public Function Leftish(s As String)
'returns first n chars which fit pattern *nn?
Dim x As Long
Dim flag As Boolean
Dim a As String
For x = 1 To Len(s)
    a = a & Mid(s, x, 1)
    If IsNumeric(Right(a, 1)) Then flag = True
    If (flag And Not IsNumeric(Right(a, 1))) Then Exit For
Next x
Leftish = a

End Function

答案 1 :(得分:0)

在此示例中,我们在列A中使用Shee1和数据属性。 试试:

Option Explicit

 Sub Test()

    Dim Lastrow As Long, i As Long
    Dim WholeString As String, Part1 As String, Part2 As String

   'Use Sheet1
    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 2 To Lastrow
            'Clean and trim the whole string
            WholeString = Application.Clean(Application.Trim(.Range("A" & i).Value))
            'Get the firts 10 characters because BACA-AA01A & BACA-AA01B has ten characters each
            Part1 = Application.Clean(Application.Trim(Left(WholeString, 10)))
            .Range("B" & i).Value = Part1
            'Get the remain characters
            Part2 = Application.Clean(Application.Trim(Mid(WholeString, 11, Len(WholeString) - 10)))
            .Range("C" & i).Value = Part2
        Next i

    End With

 End Sub

输出:

enter image description here