如果单元格在一个范围内,则进行VBA测试

时间:2011-03-03 16:12:47

标签: excel vba

我想测试给定单元格是否在Excel VBA中的给定范围内。这样做的最佳方式是什么?

6 个答案:

答案 0 :(得分:27)

来自帮助:

Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
    MsgBox "Ranges do not intersect"
Else
    isect.Select
End If

答案 1 :(得分:12)

如果要测试的两个范围(您的给定单元格给定范围)不在同一个Worksheet中,那么 {{ 1}}抛出错误。因此,避免的方法是使用类似

的方法
Application.Intersect

答案 2 :(得分:9)

Determine if a cell is within a range using VBA in Microsoft Excel

从链接网站(保留信用卡到原始提交者):

  

Erlandsen Data Consulting贡献的VBA宏观提示   提供Microsoft Excel应用程序开发,模板定制,   支持和培训解决方案

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    ' returns True if Range1 is within Range2
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function


Sub TestInRange()
    If InRange(ActiveCell, Range("A1:D100")) Then
        ' code to handle that the active cell is within the right range
        MsgBox "Active Cell In Range!"
    Else
        ' code to handle that the active cell is not within the right range
        MsgBox "Active Cell NOT In Range!"
    End If
End Sub

答案 3 :(得分:0)

@ mywolfe02给出了一个静态范围代码,所以他的inRange工作正常,但是如果你想添加动态范围,那么使用带有inRange函数的那个​​。当你想要填充数据来修复起始单元格和最后一列时,这更好用也是固定的。

Sub DynamicRange()

Dim sht As Worksheet
Dim LastRow As Long
Dim StartCell As Range
Dim rng As Range

Set sht = Worksheets("xyz")
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Set rng = Workbooks("Record.xlsm").Worksheets("xyz").Range(Cells(12, 2), Cells(LastRow, 12))

Debug.Print LastRow

If InRange(ActiveCell, rng) Then
'        MsgBox "Active Cell In Range!"
  Else
      MsgBox "Please select the cell within the range!"
  End If

End Sub 

答案 4 :(得分:0)

这是另一个选项,用于查看范围内是否存在单元格。如果你像我一样遇到Intersect解决方案的问题。

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr是一个VBA函数,用于检查字符串是否存在于另一个字符串中。

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

答案 5 :(得分:0)

我不会一直使用连续的范围。我对非连续范围的解决方案如下(包括其他答案中的一些代码):

Sub test_inters()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim inters As Range

    Set rng2 = Worksheets("Gen2").Range("K7")
    Set rng1 = ExcludeCell(Worksheets("Gen2").Range("K6:K8"), rng2)

    If (rng2.Parent.name = rng1.Parent.name) Then
        Dim ints As Range
        MsgBox rng1.Address & vbCrLf _
        & rng2.Address & vbCrLf _

        For Each cell In rng1
            MsgBox cell.Address
            Set ints = Application.Intersect(cell, rng2)
            If (Not (ints Is Nothing)) Then
                MsgBox "Yes intersection"
            Else
                MsgBox "No intersection"
            End If
        Next cell
    End If
End Sub