Correction in VBA code
Question
Below mentioned code is written by @simoco. I need a small correction. The code works for two range. I want the code to only run for columns A:E
. In other words, currently if I select a cell in any columns other than A:E
, when the code is run only two cells are selected. I do not want that to happen. If I select any cell in A:E
, I want A:E
to be selected. If I do not select a cell in columns A:E
, then code should not run and a message box should appear:
msgbox("Please select a cell in columns A:E").
Please help.
The code is:
Sub test1()
Dim rng As Range
Dim ar As Range
Dim rngAE As Range, cell As Range
With Selection
For Each ar In .Areas
If rng Is Nothing Then
Set rng = ar.Resize(1, 2)
Else
Set rng = Union(rng, ar.Resize(1, 2))
End If
Next ar
Set rngAE = Intersect(.Cells, Range("A:E"))
If Not rngAE Is Nothing Then
For Each cell In rngAE
Set rng = Union(rng, Range("A" & cell.Row & ":E" & cell.Row))
Next cell
End If
End With
rng.Select
End Sub
Solution
Try changing this:
Set rngAE = Intersect(.Cells, Range("A:E"))
If Not rngAE Is Nothing Then
For Each cell In rngAE
Set rng = Union(rng, Range("A" & cell.Row & ":E" & cell.Row))
Next cell
End If
to this:
Set rngAE = Intersect(.Cells, Range("A:E"))
If Not rngAE Is Nothing Then
For Each cell In rngAE
Set rng = Union(rng, Range("A" & cell.Row & ":E" & cell.Row))
Next cell
Else
msgbox "Please select a cell in columns A:E", vbCritical
Exit Sub
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow