循环浏览C列,然后将减去前X个字符的内容返回到B列

时间:2019-03-18 14:08:26

标签: excel vba

目标:如果列C的开头不是“ XXX *”,则返回该单元格减去前5个字符。

示例:

C2 = XXX                 Then                 B2 would be empty
C3 = YYY1220190318       Then                 B3 = 20190318
C4 = UGA1535D            Then                 B4 = 1535D 

“这是我的实际密码

  Dim arrData As Variant, LastRow As Long, i As Long, ws As Worksheet

            Set ws = ThisWorkbook.Sheets("Long List 15032019") 'change 

the name of the sheet to the one you are doing the code

        With ws
            LastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
            arrData = .Range("A2", .Cells(LastRow, "C")).Value
            For i = 1 To UBound(arrData)
                If arrData(i, 3) Like "Bus*" Then
                    arrData(i, 1) = "BU CRM"
                Else
                    arrData(i, 1) = "CSI ACE"
                End If
                If arrData(i, 3) Like "CSI*" Or arrData(i, 3) = vbNullString Then
                    arrData(i, 2) = vbNullString
                    Else: arrData(i, 2) = Right(arrData(i, 3), 12)
                End If
            Next i
            .Range("A2", .Cells(LastRow, "C")).Value = arrData

             End With

我认为这是一行代码,需要调整Else: arrData(i, 2) = Right(arrData(i, 3), 12)

我确实尝试使用-12或LEFT。但这是行不通的。

2 个答案:

答案 0 :(得分:1)

怎么样:

Sub KleanUp2()
    Dim cell As Range, v As String, v2 As String
    For Each cell In Intersect(Range("C:C"), ActiveSheet.UsedRange)
        v = cell.Value
        If Len(v) < 4 Then
            vr = ""
        Else
            vr = Mid(v, 4, 9999)
        End If
        cell.Offset(0, -1) = vr
    Next cell

End Sub

如果 C 列中的值超过3个字符,则会删除前三个字符,并将结果放在 B 列中的同一行中

如果 C 列中的值小于4个字符(或单元格为空),则在 B 在同一行中。

答案 1 :(得分:0)

尝试:

Option Explicit

Sub test()

    Dim Lastrow As Long, Row As Long

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row

            For Row = 1 To Lastrow

                If Left(.Range("C" & Row).Value, 3) = "XXX" Then
                    .Range("B" & Row).Value = ""
                Else
                    .Range("B" & Row).Value = Mid(.Range("C" & Row).Value, 4, Len(.Range("C" & Row).Value) - 3)
                End If

            Next Row

    End With

End Sub