Combining consecutive values in a column with the help of VBA

后端 未结 3 1681
一整个雨季
一整个雨季 2021-01-25 23:06

I have a data like this :

A049
A050
A051
A053
A054
A055
A056
A062
A064
A065
A066

And I want the output like :

As you can see,

3条回答
  •  难免孤独
    2021-01-25 23:31

    Try the below code

    Private Sub CommandButton1_Click()
    
        Set wb = ThisWorkbook
        lastRow = wb.Sheets("Sheet1").Range("A" & wb.Sheets("Sheet1").Rows.Count).End(xlUp).Row
        Dim lastNum, Binsert As Integer
        Dim firstCell, lastCell, currentCell As String
        Binsert = 1
        lastNum = getNum(wb.Sheets("Sheet1").Range("A1").Value)
        firstCell = wb.Sheets("Sheet1").Range("A1").Value
        For i = 2 To lastRow
            activeNum = getNum(wb.Sheets("Sheet1").Range("A" & i).Value)
            currentCell = wb.Sheets("Sheet1").Range("A" & i).Value
            If (activeNum - lastNum) = 1 Then
                'nothing
            Else
                lastCell = wb.Sheets("Sheet1").Range("A" & (i - 1)).Value
                wb.Sheets("Sheet1").Range("B" & Binsert).FormulaR1C1() = firstCell
                If (firstCell <> lastCell) Then
                    wb.Sheets("Sheet1").Range("C" & Binsert).FormulaR1C1() = lastCell
                End If
                Binsert = Binsert + 1
                firstCell = wb.Sheets("Sheet1").Range("A" & i).Value
            End If
            lastNum = activeNum
        Next i
        'last entry
        wb.Sheets("Sheet1").Range("B" & Binsert).FormulaR1C1() = firstCell
        If (firstCell <> currentCell) Then
            wb.Sheets("Sheet1").Range("C" & Binsert).FormulaR1C1() = currentCell
        End If
    End Sub
    Public Function getNum(ByVal num As String) As Integer
        getNum = Val(Mid(num, 2))
    End Function
    

提交回复
热议问题