以下是一个示例代码,实现了您的需求:

Sub ExtractCS()
    Dim currentCell As Range
    Dim inputValue As String
    Dim outputC As String
    Dim outputE As String
    Dim i As Integer
    Dim cIndex As Integer
    Dim eIndex As Integer
    
    For Each currentCell In Selection '遍历选中的单元格
        inputValue = currentCell.Value '获取单元格的值
        outputC = ""
        outputE = ""
        cIndex = 0
        eIndex = 0
        
        '寻找数字+S+C+数字+英文结构
        For i = 1 To Len(inputValue) - 4
            If IsNumeric(Mid(inputValue, i, 1)) And Mid(inputValue, i + 1, 1) = "S" And Mid(inputValue, i + 2, 1) = "C" And IsNumeric(Mid(inputValue, i + 3, 1)) And IsAlpha(Mid(inputValue, i + 4, 1)) Then
                cIndex = i + 2
                eIndex = i + 4
                Exit For
            End If
        Next i
        
        '如果找到符合条件的结构,则拆分C和英文部分
        If cIndex > 0 And eIndex > 0 Then
            outputC = Mid(inputValue, cIndex, 2)
            outputE = Mid(inputValue, eIndex, Len(inputValue) - eIndex + 1)
        End If
        
        '将结果输出到相邻的两列
        currentCell.Offset(0, 1).Value = outputC
        currentCell.Offset(0, 2).Value = outputE
    Next currentCell
End Sub

Function IsAlpha(str As String) As Boolean
    IsAlpha = str Like "[a-zA-Z]"
End Function

使用方法:

  1. 将上面的代码复制到 Excel 的 VBA 编辑器中。
  2. 选中需要处理的单元格。
  3. 运行这个宏。

注意:

  • 这个宏只处理选中的单元格。
  • 如果需要处理整个工作表,可以将 For Each currentCell In Selection 这一行改成 For Each currentCell In ActiveSheet.UsedRange

代码逻辑:

代码通过循环遍历选中的每个单元格,并对每个单元格的值进行以下操作:

  1. 寻找符合 数字+S+C+数字+英文 结构的子字符串。
  2. 如果找到符合条件的子字符串,则提取出其中的 C+数字英文 部分。
  3. 将提取出的 C+数字英文 部分分别输出到相邻的两列。

示例:

假设您要处理以下单元格内容:

| 单元格 | 内容 | |---|---| | A1 | 123S4C567xyz | | A2 | 987S1C23abc |

运行宏后,结果如下:

| 单元格 | 内容 | C+数字 | 英文 | |---|---|---|---| | A1 | 123S4C567xyz | C56 | 7xyz | | A2 | 987S1C23abc | C23 | abc |

本代码可以帮助您快速提取字符串中的特定部分,提高工作效率。您可以根据自己的需求修改代码逻辑,以实现更多功能。

Excel VBA 代码:提取字符串中 'C+数字' 和 '英文' 部分

原文地址: http://www.cveoy.top/t/topic/mJFP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录