动态生成字符(除其他字符外)并删除重复项

时间:2019-05-04 13:59:46

标签: excel excel-formula

在A列中,我具有以下数据集。

A1 :TR029A/TR029B/TR045A/TR045B
A2 :TR028A/TR028B/TR052A
A3 :TR035A/TR035B
A4 : TR045B/TR065A

可以通过以下任何方式生成B列数据。

B1: TR029/TR045
B2: TR028/TR052
B3: TR035
B4: TR045/TR065

2 个答案:

答案 0 :(得分:1)

我想,如果您需要这种控制级别,则必须使用VBA创建excel函数

  • 按ALT + F11进入VBA视图
  • 右键单击VBAProject>插入>模块
  • 将打开一个窗口,您可以在其中键入VBA代码

将此VBA代码复制到打开的窗口中,以创建所需的新功能GenChars:

Option Explicit

Function GenChars(value As String)
    ' an array of individual elements that were delemited by "/"
    Dim xs() As String
    xs = Split(value, "/")

    ' remove the last character from each element or replace it with @ if it would be a duplicate
    Dim i As Long
    For i = LBound(xs) To UBound(xs)
        Dim x As String
        x = xs(i)
        x = Left$(x, Len(x) - 1) ' remove last char
        If ArrayContains(xs, x) Then x = "@" ' replace duplicate elements with @
        xs(i) = x
    Next i

    Dim value2 As String
    ' new value with duplicates
    value2 = Join(xs, "/") ' put the elements back into 1 value
    ' remove @ that was used instead of duplicates
    value2 = Replace(value2, "/@", "") ' remove occurrences of /@ (1st element is never duplicate)

    GenChars = value2
End Function

' whether array xs contains element y
Function ArrayContains(xs As Variant, y As Variant) As Boolean
    ArrayContains = False

    Dim x As Variant
    For Each x In xs
        If x = y Then ArrayContains = True
    Next x
End Function
  • 再次按ALT + F11返回正常视图
  • 要使用它,例如进入单元格B1并输入: = GenChars(A1)

答案 1 :(得分:1)

只需发布此图片即可证明共生体代码有效:

enter image description here

安装说明正确无误,做得好。

在col F中添加了相同的功能:

enter image description here