Sub MergeSelectedRange()
'Declare variables
Dim rng As Range
Dim cell As Range
Dim lastCell As Range
Dim currentValue As String
Dim lastValue As String
'Prompt the user to select the range
Set rng = Application.InputBox("Select the range to merge:", Type:=8)
'Initialize the lastValue variable
lastValue = rng.Cells(1, 1).Value
'Loop through the selected range
For Each cell In rng
currentValue = cell.Value
If currentValue = lastValue Then
'If the current cell has the same value as the last cell, add it to the range
If lastCell Is Nothing Then
Set lastCell = cell
Else
Set lastCell = Union(lastCell, cell)
End If
Else
'If the current cell has a different value than the last cell, merge the range
If Not lastCell Is Nothing Then
lastCell.Merge
Set lastCell = Nothing
End If
lastValue = currentValue
End If
Next cell
End Sub
"This code will prompt the user to select a range and then search that range for cells that have the same value and merge them together, with the last cell to the right.
You can run this code by opening the Visual Basic Editor (VBE) by clicking on Developer tab and then clicking on Visual Basic or by pressing ALT + F11 and then running the code by clicking on the Run button or by pressing F5.
It's important to note that, this will only merge the adjacent cells with the same value, and it will not work if there are any empty cell in between. Also, this code will merge all the cells in the selected range, including empty cells and cells with different formats.
EXCEL తెలుగు HYDERABAD TELANGANA
Comments
Post a Comment