用于组合文本字符串的常见部分的代码

时间:2016-03-04 12:41:23

标签: excel vba excel-vba

如果我在电子表格中有一个字符串列表,有没有办法将它们组合起来只保留它们共有的字符串?例如,如果我有这个清单:

C- D2 Carbon steel column  1   7.58   0.47    1.15    1,096.00
C-E1 Carbon steel column   1   7.58   0.47    1.15    1,096.00
C- E2 Carbon steel column  1   7.58   0.47    1.15    1,096.00
C-F1 Carbon steel column   1   7.58   0.47    1.15    1,096.00
C-F2 Carbon steel column   1   7.58   0.47    1.15    1,096.00
C-G1 Carbon steel column   1   7.58   0.47    1.15    1,096.00
C-G2 Carbon steel column   1   7.58   0.47    1.15    1,096.00
C-H1 Carbon steel column   1   7.58   0.47    1.15    1,096.00

...我希望将其合并到

Carbon steel column        8   7.58   0.47    1.15    1,096.00

执行数字不是问题,但如何获取文本字符串的常用元素?

编辑:澄清一下,目的是找到共同的元素,而不仅仅是将它们分开。不幸的是,事先并不知道结束短语。

2 个答案:

答案 0 :(得分:1)

在B11:B12中作为其中一个SUMIF functions

=SUMIF($A$2:$A$9, "*Carbon steel column", B$2:B$9)     '◄ B11
=SUMIF($A$2:$A$9, "*"&$A12, B$2:B$9)                   '◄ B12

请注意前缀通配符星号。这意味着A列将以碳钢柱结束。填写额外的列总数。用AVERAGEIF function或其他一些聚合函数替换以获得所需的结果。

carbno_steel_column

答案 1 :(得分:0)

您可以尝试拆分其组件中的第一个单元格(假设是空格),并添加集合中的所有单词。然后,对于每个其他单元格,将其拆分并检查集合是否已有单词。如果没有,请将其从集合中删除。

Dim MyCollection As Collection
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim bIsInArray As Boolean
Dim sFinalString As String


Private Sub CommandButton1_Click()
lLastRow = Cells(Rows.Count, 1).End(xlUp).Row 'get the number of rows with data
Set MyCollection = New Collection
ReDim MyArray(1 To 1) As String
For i = 2 To lLastRow 'Assuming your data starts in A2 (A1 being titles)
    If i = 2 Then 'The first data cell
        MyArray = Split(Worksheets("Data").Cells(i, 1).Value, " ") 'split the cell using spaces as spliting character
        For j = 0 To UBound(MyArray)
            MyCollection.Add (MyArray(j)) 'add all words to collection
        Next
    Else 'if is not the first cell of data
        ReDim MyArray(1 To 1) As String 'set a "new" array
        MyArray = Split(Worksheets("Data").Cells(i, 1).Value, " ")

        For j = MyCollection.Count To 1 Step -1
            bIsInArray = False
            For k = 0 To UBound(MyArray)
                If MyCollection.Item(j) = MyArray(k) Then
                    bIsInArray = True
                End If
            Next
            If bIsInArray = False Then
                MyCollection.Remove (j)
            End If
        Next

    End If
Next
'Now MyCollection contains all common words

sFinalString = ""
For j = 1 To MyCollection.Count
    sFinalString = sFinalString & " " & MyCollection.Item(j)
Next
Worksheets("Data").Cells(lLastRow + 2, 1).Value = sFinalString
End Sub