VBAtesting如果单元格在一个范围内

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

从帮助:

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

如果要testing的两个范围(您的给定单元格和您的给定范围 )不在同一个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 

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

从链接的网站(保持信贷到原来的提交者):

由Erlandsen Data Consulting提供的VBAmacros提示提供Microsoft Excel应用程序开发,模板定制,支持和培训解决scheme

 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 

@ mywolfe02给出了一个静态范围代码,所以他的inRange工作正常,但是如果你想添加dynamic范围,那么使用这个与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 

这里是另一个选项,看看一个单元格是否存在于一个范围内。 如果您遇到与Intersect解决scheme相关的问题。

 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函数,用于检查另一个string中是否存在string。

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