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

lov*_*ubs 12 excel vba

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

Pat*_*rez 29

来自帮助:

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


san*_*ica 13

如果要测试的两个范围(您的给定单元格给定范围)不相同Worksheet,则会Application.Intersect抛出错误.因此,一种避免它的方法就是这样

Sub test_inters(rng1 As Range, rng2 As Range)
    If (rng1.Parent.Name = rng2.Parent.Name) Then
        Dim ints As Range
        Set ints = Application.Intersect(rng1, rng2)
        If (Not (ints Is Nothing)) Then
            ' Do your job
        End If
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)


mwo*_*e02 9

使用Microsoft Excel中的VBA确定单元格是否在范围内:

从链接的站点(保持信用到原始提交者):

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
Run Code Online (Sandbox Code Playgroud)

  • 增加的价值是提高客户端代码的清晰度和减少混乱.费用是额外的图书馆代码.辅助库代码越来越有用,因为它的使用越多,客户端代码的整体复杂性也越来越高.此外,我将InRange修剪为"InRange = Not Application.Intersect(Range1,Range2)Nothing".附加变量增加了比保存更多的复杂性. (3认同)
  • 为什么将原始函数封装到另一个只是降低其功能而没有任何附加值的函数?这是一个完美的例子"无用的脂肪编程". (2认同)