Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 找出所选单元格是否在DataCodeRange中_Excel_Vba - Fatal编程技术网

Excel 找出所选单元格是否在DataCodeRange中

Excel 找出所选单元格是否在DataCodeRange中,excel,vba,Excel,Vba,我设置了一个宏来执行“onclick”事件中的一段代码,我试图确定他们是否在表范围内选择了一个数值。下面是我的表的一个例子,我试图弄清楚他们是否在第二列中选择了一个大于0的数字。我知道如何引用特定表的第二列,例如: ListObjects("Table1").ListColumns(2).DataBodyRange 但我不确定如何确定所选单元格是否在该范围内。有什么建议吗?非常感谢你的帮助 使用Intersect Dim rangeToCheck as Range Set rangeToChe

我设置了一个宏来执行“onclick”事件中的一段代码,我试图确定他们是否在表范围内选择了一个数值。下面是我的表的一个例子,我试图弄清楚他们是否在第二列中选择了一个大于0的数字。我知道如何引用特定表的第二列,例如:

ListObjects("Table1").ListColumns(2).DataBodyRange
但我不确定如何确定所选单元格是否在该范围内。有什么建议吗?非常感谢你的帮助


使用
Intersect

Dim rangeToCheck as Range
Set rangeToCheck = Intersect(ActiveCell, ListObjects("Table1").ListColumns(2).DataBodyRange)

If Not rangeToCheck Is Nothing Then
    If IsNumeric(ActiveCell.Value) Then 
        If ActiveCell.Value > 0 Then
            ' do the suff
        End If
    End If
End If

使用
Intersect

Dim rangeToCheck as Range
Set rangeToCheck = Intersect(ActiveCell, ListObjects("Table1").ListColumns(2).DataBodyRange)

If Not rangeToCheck Is Nothing Then
    If IsNumeric(ActiveCell.Value) Then 
        If ActiveCell.Value > 0 Then
            ' do the suff
        End If
    End If
End If

假设您的表有过滤器,那么您只需检查可见单元格

请尝试以下代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.EnableEvents = False

    Dim r As Range
    Set r = ListObjects(1).ListColumns(2).DataBodyRange.SpecialCells(xlCellTypeVisible)

    Dim hit As Boolean
    hit = Not Application.Intersect(r, Target) Is Nothing

    If hit Then
        Range("A1").Value = "Inside"
    Else
        Range("A1").Value = "Outside"
    End If

    Application.EnableEvents = True

End Sub
否则,对于所有可见和不可见单元格,请使用

Set r = ListObjects(1).DataBodyRange

假设您的表有过滤器,那么您只需检查可见单元格

请尝试以下代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.EnableEvents = False

    Dim r As Range
    Set r = ListObjects(1).ListColumns(2).DataBodyRange.SpecialCells(xlCellTypeVisible)

    Dim hit As Boolean
    hit = Not Application.Intersect(r, Target) Is Nothing

    If hit Then
        Range("A1").Value = "Inside"
    Else
        Range("A1").Value = "Outside"
    End If

    Application.EnableEvents = True

End Sub
否则,对于所有可见和不可见单元格,请使用

Set r = ListObjects(1).DataBodyRange

您不需要同时指定
列表列(2)
吗?太好了,谢谢@BigBen和ja72的建议!我不知道intersect的存在。你不需要同时指定
ListColumns(2)
吗?太好了,谢谢@BigBen和ja72的建议!我不知道存在着交集。