Code :
Option Explicit
Sub selectAdjacentBelowCells()
Dim r, c As Integer
Dim r1, r2, c1, c2 As Integer
Dim i As Integer
Dim j As Integer
Dim st As String
Dim lastRow As Integer
With ActiveCell
r = .Row
c = .Column
End With
r1 = r
r2 = r
lastRow = ActiveSheet.Cells(Rows.Count, c).End(xlUp).Row
Dim value As Integer
value = Cells(r, c).value
Dim value1 As Integer
Dim value2 As Integer
Dim myUnion As Range
Dim myCell As Range
For i = r1 To lastRow - 1
'selects adjacent cells below
value1 = Cells(i + 1, c).value
If (value1 = value) Then
Range(Cells(i, c), Cells(i + 1, c)).Select
Else
Exit For
End If
Next
Dim x As Integer
x = Cells(r2 - 1, c).value
For x = r2 To (r2 + 1) - r2 Step -1
'selects adjacent cells above
value2 = Cells(x - 1, c).value
If (value2 = value) Then
Range(Cells(r, c), Cells(x - 1, c)).Select
Else
Exit For
End If
Next
End Sub
Column in excel :
10
20
30
40
50
60
60(this cell is selected and then vba code is executed)
60
70
80
90
I need to select adjacent cells in entire column. It selects adjacent cells, but first it selects adjacent cells below and then above. But the selection changes to above cells and below cells are deselected after the first piece of code runs.
I know it can be done through Union
, I tried using it but I got errors everytime. Got argument is not optional
error and then I had to remove the Union
code and the above code is what I now have.