Code Explainer | VBA

Excel VBA Subroutine for Row Combination

This VBA code combines rows in an Excel worksheet based on equal values in the first column, concatenating cell data from duplicate rows and deleting the originals to streamline data management.


Empty image or helper icon

Prompt

Sub CombineRows()
    Dim ws As Worksheet
    Dim i As Integer
    Dim lastRow As Long
    Dim j As Integer

    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    For i = lastRow To 2 Step -1
        If ws.Cells(i, 1).Value = ws.Cells(i - 1, 1).Value Then
            For j = 2 To ws.Columns.Count
                If ws.Cells(i, j).Value <> "" Then
                    ws.Cells(i - 1, j).Value = ws.Cells(i - 1, j).Value & " " & ws.Cells(i, j).Value
                End If
            Next j
            ws.Rows(i).Delete
        End If
    Next i
End Sub

Answer

Code Explanation: Sub CombineRows()

The provided code snippet is written in VBA (Visual Basic for Applications), specifically designed to run within Microsoft Excel. The primary function of this code is to combine rows in an Excel worksheet based on the values in the first column.

Code Structure and Functionality

1. Variable Declarations

Dim ws As Worksheet
Dim i As Integer
Dim lastRow As Long
Dim j As Integer
  • ws: A variable of type Worksheet, used to reference the active worksheet where the operation will be performed.
  • i: An integer used as a loop counter.
  • lastRow: A long integer that stores the number of the last row containing data in column A.
  • j: An integer used as a loop counter for columns.

2. Setting Active Worksheet and Last Row

Set ws = ActiveSheet
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
  • Set ws = ActiveSheet: This line assigns the currently active worksheet to the variable ws.
  • lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row: This code determines the last row with data in column A. It counts from the bottom of the column upwards until it finds a non-empty cell.

3. Main Loop to Combine Rows

For i = lastRow To 2 Step -1
  • This loop iterates through the rows, starting from lastRow down to row 2 (i.e., it skips row 1, which typically contains headers). Step -1 indicates that it decreases i by 1 in each iteration.

4. Checking for Equal Values

If ws.Cells(i, 1).Value = ws.Cells(i - 1, 1).Value Then
  • This condition checks if the value in the current row (i) of the first column (Column A) is equal to the value in the previous row (i-1) of the same column. If they are equal, it implies that these rows should be combined.

5. Combining Row Values

For j = 2 To ws.Columns.Count
    If ws.Cells(i, j).Value <> "" Then
        ws.Cells(i - 1, j).Value = ws.Cells(i - 1, j).Value & " " & ws.Cells(i, j).Value
    End If
Next j
  • An inner loop iterates through each column of the current row (starting from column 2).
  • If ws.Cells(i, j).Value <> "" Then: This checks if the cell in the current row and column is not empty.
  • If it is not empty, the code concatenates the value in the current cell with the existing value in the previous row's corresponding cell, separated by a space.

6. Deleting the Combined Row

ws.Rows(i).Delete
  • Once the values are combined, the entire current row (i) is deleted from the worksheet.

7. End of Main Loop

Next i
  • This signifies the end of the for loop and will continue until all relevant rows have been processed.

Key Concepts Explained

  • Looping: The use of loops (both for and if) is essential in programming for processing sequences of data. In this scenario, it allows the code to check and process each row systematically.

  • String Concatenation: The & operator in VB is used to concatenate (combine) strings. It plays a critical role in merging values from multiple cells.

  • Row Deletion: Deleting rows during iteration should be done carefully to avoid skipping rows. This example deletes rows in reverse order to maintain row integrity.

Alternative Example

If a user wishes to combine rows based on conditions other than equality, they could modify the comparison in the if statement. For instance, if combining based on a specific threshold:

If ws.Cells(i, 1).Value > THRESHOLD_VALUE Then
    ' Combine rows logic
End If

In this example, THRESHOLD_VALUE would represent a specific numeric or string threshold.

Conclusion

The CombineRows subroutine effectively compresses data within an Excel worksheet by carrying forward values from duplicate rows into a single entry. Understanding how to manipulate and iterate through Excel sheets using VBA greatly enhances one's data processing capabilities. Further knowledge and exploration can be gained through the courses offered on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This VBA code combines rows in an Excel worksheet based on equal values in the first column, concatenating cell data from duplicate rows and deleting the originals to streamline data management.