恒定长度的数字和字母串

时间:2014-01-15 15:19:12

标签: string excel excel-vba numbers vba

我想在一列格式相同的字符串中搜索错误:(示例:B2013JMSL10764B2013JMSL11030)。

错误我指的是字母应该是数字,反之亦然,例如:字母O而不是数字0

是否可以找到有错误的所有字符串并将它们复制到新列中,但是找到它们的同一行。

感谢。我对如何处理这个问题,或者可能需要的一些技巧和代码行感兴趣。

这是我到目前为止所做的:

Sub sampleNoCheck()

    Sheets("sheet1").Activate
    Dim uColumn As String

    ' if your data is in a different column then change A to some other letter(s)
    uColumn = "j"

    Dim i As Long, j As Long, r As Range
    For i = 2 To Range(uColumn & Rows.Count).End(xlUp).Row
        Set r = Range(uColumn & i)

        {Dim part1 As String, part2 As Integer, part3 As String, part6 As String, part7 As String, part8 As String, part4 As Integer

        If Len(r) = 14 Then
            part1 = Left(r, 1)
            part2 = Mid(r, 2, 5)
            part3 = Mid(r, 6, 6)
            part6 = Mid(r, 7, 7)
            part7 = Mid(r, 8, 8)
            part8 = Mid(r, 9, 9)
            part4 = Right(r, 5)

        ElseIf Len(r) = 15 Then 'possibility of having an extra text digit 
            Dim part5 As String
            part1 = Left(r, 1)
            part2 = Mid(r, 2, 5)
            part3 = Mid(r, 6, 6)
            part6 = Mid(r, 7, 7)
            part7 = Mid(r, 8, 8)
            part8 = Mid(r, 9, 9)
            part4 = Mid(r, 10, 14)
            part5 = Right(r, 1)
        Else
            MsgBox "error in row " & i
        End If

        If IsText(part1) = true And IsNumber(part2) = True And IsText(part3) = True And IsText(part6) = True And IsText(part7) = True And IsText(part8) = True And IsNumber(part5) = True And (part5 = d Or part5 = e Or part5 = f) Then

    Next i

    Else
        MsgBox "error in row " & i

End Sub

1 个答案:

答案 0 :(得分:0)

对不起,我的帖子不专业,我终于可以将一个混乱的代码放在一起,大部分工作都是以下代码检查错误,并在发现错误时提供反馈:

Sub sampleNoCheck()

Sheets("sheet1").Activate
    Dim uColumn As String

    ' if your data is in a different column then change A to some other letter(s)
    uColumn = "A"

    Dim i As Long, j As Long, r As Range
For i = 2 To Range(uColumn & Rows.Count).End(xlUp).Row
        Set r = Range(uColumn & i)
Dim part1 As String, part2 As String, part3 As String, part6 As String, part7 As String, part8 As String, part4 As Integer, part5 As String
If Len(r) = 14 Then
part1 = Left(r, 1)
part2 = Mid(r, 2, 4)
part3 = Mid(r, 6, 1)
part6 = Mid(r, 7, 1)
part7 = Mid(r, 8, 1)
part8 = Mid(r, 9, 1)
part4 = Right(r, 5)

ElseIf Len(r) = 15 Then

part1 = Left(r, 1)
part2 = Mid(r, 2, 4)
part3 = Mid(r, 6, 1)
part6 = Mid(r, 7, 1)
part7 = Mid(r, 8, 1)
part8 = Mid(r, 9, 1)
part4 = Mid(r, 10, 5)
part5 = Right(r, 1)

Else: MsgBox "Insuffficient number of code digits in row " & i
End If
If IsNumeric(part1) = False And IsNumeric(part2) = True And IsNumeric(part3) = False And IsNumeric(part6) = False And IsNumeric(part7) = False And IsNumeric(part8) = False And IsNumeric(part4) = True And (part5 = D Or part5 = E Or part5 = F Or part5 = Null) Then
GoTo nextiteration
Else
MsgBox "error " & i
End If
nextiteration:
Next i

End Sub