我需要一个excel的vba逻辑是当字符中出现数字+S+C+数字+英文结构时把其中C+数字和英文分别拆分出来
以下是一个示例代码,实现了您的需求:
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 = "" '初始化C部分的输出
outputE = "" '初始化英文部分的输出
cIndex = 0 '初始化C部分的位置
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 '记录C部分的位置
eIndex = i + 4 '记录英文部分的位置
Exit For '退出循环
End If
Next i
'如果找到符合条件的结构,则拆分C和英文部分
If cIndex > 0 And eIndex > 0 Then
outputC = Mid(inputValue, cIndex, 2) '获取C部分的值
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
使用方法:将上面的代码复制到Excel的VBA编辑器中,然后选中需要处理的单元格,运行这个宏即可。这个宏会将每个符合条件的单元格的值拆分成C和英文两部分,并将它们输出到相邻的两列中。注意,这个宏只处理选中的单元格。如果需要处理整个工作表,可以将“For Each currentCell In Selection”这一行改成“For Each currentCell In ActiveSheet.UsedRange”。
原文地址: https://www.cveoy.top/t/topic/bhQm 著作权归作者所有。请勿转载和采集!