将单元格格式化为仅显示X个字符后的字符

时间:2019-03-18 09:26:11

标签: excel vba

不是从右边接收前12个字符,而是需要一个没有前12个字符的单元格。

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

即如果C3 =“示例(ID:15654534)”,则B3 =“(ID:15654534)”;或者如果C3 =“示例(ID:152)”,则B3 =“(ID:152)”

我确实尝试使用Left或-12。但是结果不是我所需要的。 我希望这可以澄清我的问题。

谢谢

2 个答案:

答案 0 :(得分:1)

听起来像您想要的正则表达式。在这种情况下,您将拥有

arrData(i,2) =  GetId(arrData(i, 3) , "ID:\d+")

代码:

Option Explicit

Public Sub test()
    Dim items(), item As Variant
    items = Array("Example (ID:15654534)", "Example (ID:152)")
    For Each item In items
        Debug.Print GetId(item, "ID:\d+")
    Next
End Sub
Public Function GetId(ByVal inputString As String, ByVal sPattern As String) As String
    Dim matches As Object, iMatch As Object, arrMatches(), i As Long
    i = 1
    With CreateObject("vbscript.regexp")
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = sPattern
        If .test(inputString) Then
            Set matches = .Execute(inputString)
            ReDim arrMatches(1 To matches.Count)
            For Each iMatch In matches
                arrMatches(i) = iMatch.Value
                i = i + 1
            Next iMatch
        Else
            GetId = "No match"
            Exit Function
        End If
    End With
    GetId = arrMatches(1)
End Function

答案 1 :(得分:0)

这可以在没有VBA的情况下完成,但前提是输入是相同的结构。您的数据现在是:

text(idnumber),而您只想获取包含两个括号的部分(idnumber )。

该公式仅在数据结构相同的情况下有效。如果输入更改了某些内容,它将无法正常工作(例如,如果缺少第一个括号,则它将无法正常工作)。

我使用的公式是这个:

=MID(C1;SEARCH("(";C1;1);SEARCH(")";C1)-SEARCH("(";C1;1)+1)

我的数据示例:

enter image description here

希望您可以根据需要对其进行调整。