2017-06-16 67 views
1

我试图在包含客户端的移动号码的范围上替换数字。我想更改不是6位数,7位数,10位数和11位数的数字,我也想更改其前3位数不是“032”的10位数字。这是我到目前为止:根据长度和前3个字符替换数字

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

+1

请告诉我你的问题?你的问题? – UGP

+2

(1)“*我想改变数字*”并不能很好地描述你想达到的目标。你需要更具体。 [编辑]你的问题,并添加你的代码实际上做什么和你期望它做什么,如果有任何错误(哪里和哪些错误)。你可能会读[问]。 (2)附注(不是解决方案):如果你这样做'Dim lastrow,i,currentcell As Long'只有最后一个变量是'Long'其他是'Variant'你需要指定一个类型**每个* *变量:'Dim lastrow As Long,I As Long,currentcell As Long' –

+0

如果这些是**数字**(而不是文本),第一个字符将如何成为“0”?如果您有具有特定单元格格式的数字,您可能需要考虑使用'.Text'属性。 – YowE3K

回答

1

sTxt = ActiveSheet.Range( “CW” & 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 
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 
+0

@SiddharthRout:谢谢。我错了。 –

+0

++'cse 10'应该是'Case 10'。你也有很多不必要的代码,你可以摆脱:)。我已修复您的帖子。如果你不喜欢,随时回复它 –

+0

@SiddharthRout:谢谢。因为,我也没有测试。有薄雾。 –

相关问题