2017-09-27 8 views
2

Excel에서 범위로 정의 된 3x3 범위가 있습니다. 파란색 셀을 두 번 클릭했을 때 사용자가 클릭 한 위치를 알고 싶습니다. - 영역은 범위로 정의됩니다.Excel VBA는 activeCell에 상대적인 3X3 범위의 위치를 ​​결정합니다.

enter image description here

내 기본적인 기술에 대한하지만 그 조금 어려운,이 선택을 발견하는 함수를 만들려고했다.

제 생각에는 매트릭스의 각 셀에 정수 값 (1 - 9)을 할당하고 해당 값을 반환하는 함수가 있어야합니다. 제공 대답

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 

에 따라

편집 질문은 이제 작업이 기능을 가지고, 쉬운 방법이 아니 었 놀랐습니다.

답변

2

표준 모듈이 아닌 시트 객체에 있어야합니다.

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 

Cancel = True이면 셀이 편집 모드가 아닙니다.

Target에서 범위를 가져 와서 비교할 수 있습니다.

+0

감사합니다. 이 솔루션은 나와 함께 작동합니다. 그러나, 나는이 많은 행렬 뷰가 있음을 언급하는 것을 잊어 버렸고, 나는 일하는 일반적인 방법을 정의하려고 시도했다. 현재 주소는 범위를 기준으로하지 않고 시트와 관련이 있습니다. – Hightower

+0

@Hightower 코드를 업데이트했습니다. 'Matrix (i) '범위에서 각 3x3 블록에 대한 새로운 범위를 만들 것입니다. –