根据长度和前三名字符replace数字

我正在尝试在包含移动号码的客户端范围内replace号码。 我想改变不是6位数字,7位数字,10位数字和11位数字的数字,我也想改变前3位数字不是“032”的10位数字。 这是我迄今为止所提出的:

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 

代码确实改变了单元格,但问题在于它不准确。 我想知道这将如何正确完成,如下面的示例图片:

初始数据

期望的结果

我认为代码会是这样的

 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 

sTxt = ActiveSheet.Range(“CW”&currentcell).Value

没有任何事情发生,因为您正在将值存储在variables中,对其进行更改,但不会将其写回到单元格中。

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

这是你正在尝试? ( 未经testing

 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