【问题标题】:Excel VBA determine the location of a 3X3 range relative to activeCellExcel VBA确定3X3范围相对于activeCell的位置
【发布时间】:2017-09-27 22:57:22
【问题描述】:

我在 Excel 中有一个 3 x 3 的范围,它被定义为一个范围。我想知道双击任何蓝色单元格时用户点击了哪里。 - 该区域被定义为一个范围。

我试图创建一个函数来找出这个选择,但这对我的基本技能来说有点困难。

我的想法是为矩阵中的每个单元格分配一个整数值 (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

我现在有这个功能,很惊讶没有更简单的方法。

【问题讨论】:

    标签: excel spreadsheet vba


    【解决方案1】:

    这应该在您的工作表对象中,而不是在标准模块中。

    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 中获取范围并与之进行比较。

    【讨论】:

    • 谢谢。这个解决方案适用于我。但是,我忘了提到我有很多这样的矩阵视图,我试图定义一种通用的工作方式。目前,地址是相对于工作表的,而不是相对于范围的。
    • @Hightower 我更新了我的代码。您将为 Matrix(i) 范围内的每个 3x3 块创建一个新范围。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多