简体   繁体   中英

How do I convert a series of mixed text and number values to a single string with consecutive number values summed?

For values:

1, 1, A, B, 2, 1, C, C, 3, D, 1, 1, 1

How would a create a single string:

2AB3CC3D3 (not 11AB21CC3D111)

Try this ...

Public Function SummateAllNumbers(ByVal rngCells As Range, Optional ByVal bSplitCellContents As Boolean = False, Optional ByVal strDelimiter As String = ",") As String
    Dim rngCell As Range, arrValues() As String, lngIndex As Long, arrSplitValues() As String
    Dim i As Long, lngSummation As Long, strValue As String

    lngIndex = -1

    For Each rngCell In rngCells
        If bSplitCellContents Then
            arrSplitValues = Split(rngCell.Value, strDelimiter)
        Else
            arrSplitValues = Split(rngCell.Value)
        End If

        For i = 0 To UBound(arrSplitValues)
            lngIndex = lngIndex + 1
            ReDim Preserve arrValues(lngIndex)
            arrValues(lngIndex) = arrSplitValues(i)
        Next
    Next

    For i = 0 To UBound(arrValues)
        strValue = Trim(arrValues(i))

        If IsNumeric(arrValues(i)) Then
            lngSummation = lngSummation + strValue
        Else
            If lngSummation > 0 Then
                SummateAllNumbers = SummateAllNumbers & lngSummation
            End If

            SummateAllNumbers = SummateAllNumbers & strValue
            lngSummation = 0
        End If

        If i = UBound(arrValues) And lngSummation > 0 Then
            SummateAllNumbers = SummateAllNumbers & lngSummation
        End If
    Next
End Function

... you need add the above to a new Module with the VBA Editor.

You can use it 3 ways.

Single Cell Delimited

单细胞法

You can specify it against a single cell and have the function split the contents of the cell into an array so as to identify individual elements.

Range Selection

范围选择

Omit the part of the formula that specifies that you want to split the contents of the cell by a specific delimiter and select a range of cells.

Combination of Both

在此处输入图片说明

You can do both.

If you don't see it, there's also a 3rd parameter to change the delimiter if you need that option.

I didn't get your answer to whether or not the values are in different cells so I catered for both.

I hope it works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM