根据长度和前3个字符替换数字

时间:2017-06-16 07:02:33

标签: excel vba excel-vba

我试图替换包含移动号码客户端的范围内的号码。我想更改不是6位数字,7位数字,10位数字和11位数字的数字,我也想更改10位数字,其前3位数字不是" 032" 。这是我到目前为止所得到的:

Sub changetold()
    Dim rCel As Range
    Dim sTxt As String
    Dim first3numbers As String
    Dim lastrow, i, currentcell As Long

    Const MaxLength As Long = 11
    Const MinLength As Long = 6
    Const MidLength As Long = 7
    Const MaxmidLength As Long = 10

    first3numbers = "032"

    With ActiveSheet
        lastrow = .Cells(.Rows.count, "AC").End(xlUp).row
    End With

    currentcell = 12

    For i = 13 To lastrow
        currentcell = currentcell + 1
        sTxt = ActiveSheet.Range("CW" & currentcell).Value

        MsgBox (Len(sTxt))

        If Len(sTxt) <> MaxLength Or Len(sTxt) <> MinLength Or Len(sTxt) <> MidLength Or Len(sTxt) <> MaxmidLength Then
            sTxt = "101011"
        End If

        If Left(sTxt, 3) <> "032" And Len(sTxt) = MaxmidLength Then
            sTxt = "101011"
        End If
    Next i
End Sub

代码确实改变了单元格,但问题是它是不准确的。我想知道如何正确完成这项工作,如下图所示:

Initial data

Desired result

2 个答案:

答案 0 :(得分:3)

我认为代码就像这样

Sub changetold()
    Dim sTxt As String
    Dim lastrow As Long, i As Long

    With ActiveSheet
        lastrow = .Cells(.Rows.Count, "AC").End(xlUp).Row
    End With

    For i = 13 To lastrow
        sTxt = Range("CW" & i)

        Select Case Len(sTxt)
        Case 6, 7, 11
        Case 10
            If Left(sTxt, 3) <> "032" Then Range("cw" & i) = "101011"
        Case Else
            Range("cw" & i) = "101011"
        End Select
    Next i
End Sub

答案 1 :(得分:2)

  

sTxt = ActiveSheet.Range(&#34; CW&#34;&amp; currentcell).Value

没有任何事情发生,因为您将值存储在变量中,对其进行更改但从未将其写回单元格。

使用Ifs,而不是使用这么多Select Case。它会让你的生活更轻松:)

这是你在尝试什么? (的未测试

Sub changetold()
    Dim lastrow As Long, i As Long

    With ActiveSheet
        lastrow = .Cells(.Rows.Count, "AC").End(xlUp).Row

        For i = 13 To lastrow
            Select Case Len(.Range("CW" & i).Value)
                Case 6, 7, 11
                Case 10: If Left(.Range("CW" & i).Value, 3) <> "032" Then .Range("CW" & i).Value = 101011
                Case Else: .Range("CW" & i).Value = 101011
            End Select
        Next i
    End With
End Sub