Reputation: 1008
I have a 3 x 3 range in Excel which is defined as a range. I would like to know where the user has clicked when double-clicking in any of the blue cells. - the area is defined as a range.
I have tried to create a function to find out this selection, however its a little difficult for my basic skills.
my idea is to assign an integer value (1 - 9) to each cell in the matrix and have a function to return that value.
Edited question based on provided answer
Function relRange(rangeIn As Range, activeCell) As Integer
relRange = 0
If (rangeIn.Rows.Count = 6) And (rangeIn.Columns.Count = 6) Then ' range has double merged cells
' comparison code to determine where the activecell is relative to the 3x3 array
If rangeIn.Cells(5, 1).Address = activeCell Then relRange = 1 '1
If rangeIn.Cells(3, 1).Address = activeCell Then relRange = 2 '2
If rangeIn.Cells(5, 3).Address = activeCell Then relRange = 3 '3
If rangeIn.Cells(3, 3).Address = activeCell Then relRange = 4 '4
If rangeIn.Cells(1, 1).Address = activeCell Then relRange = 5 '5
If rangeIn.Cells(5, 5).Address = activeCell Then relRange = 6 '6
If rangeIn.Cells(1, 3).Address = activeCell Then relRange = 7 '7
If rangeIn.Cells(3, 5).Address = activeCell Then relRange = 8 '8
If rangeIn.Cells(1, 5).Address = activeCell Then relRange = 9 '9
End If
End Function
I have this function working now, was surprised that there was not an easier way.
Upvotes: 2
Views: 128
Reputation: 10139
This should be in your Sheet Object, not in a standard module.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets(1)
Dim Matrix(1 To 2) As Range, i As Long
Set Matrix(1) = ws.Range("A1:C3")
Set Matrix(2) = ws.Range("F1:H3")
For i = LBound(Matrix) To UBound(Matrix)
Set iSect = Application.Intersect(Target, Matrix(i))
If Not iSect Is Nothing Then
Exit For
End If
Next
If Not iSect Is Nothing Then
MsgBox "Target located in Range # " & i & " at: " & Target.Address
Else
MsgBox "Does NOT interesect in any of my ranges!"
End If
Cancel = True
End Sub
If Cancel = True
, then your cell will not be in editing mode.
You can take the range from Target
and make your comparisons with that.
Upvotes: 3