我有两个范围。我试图找出他们的价值是否有重叠。是否有内置的“应用程序”功能,可以查找两个范围内的值是否重叠?或者我需要做这样的事情,其中我有两组for循环和某种逻辑,用于测试rcellA
(范围A中的单元格)是否与rcellB
重叠(范围B中的单元格) )?
Set rngA = loopset.range("A2-A999")
Set rngB = loopset.range("B2-B999")
For Each rcellA in rngA.cells
For Each rcellB in rngB.cells
Next rcellB
Next rcellA
答案 0 :(得分:0)
我不会在
之后得到你真正的重叠所以这里有一些镜头
返回具有相同相对位置和值的两个范围中的单元格数:
Function CheckRangesOverlap1(rng1 As Range, rng2 As Range, overlaps As Long) As Boolean
Dim cell As Range
Dim firstRow As Long, firstColumn As Long, iRow As long, iColumn As Long
firstRow = rng1.Rows(1).Row - 1
firstColumn = rng1.Columns(1).Column - 1
For Each cell in rng1.SpecialCells(xlCellTypeConstants)
iRow = cell.Row - firstRow
iColumn = cell.Column - firstColumn
If rng2(iRow, iColumn).Value = cell.Value Then overlaps = overlaps + 1
Next
CheckRangesOverlap1 = overlaps > 0
End Function
返回具有相同相对位置和值的两个范围中的单元格范围:
Function CheckRangesOverlap2(rng1 As Range, rng2 As Range, overlapRng As Range) As Boolean
Dim cell As Range
Dim firstRow As Long, firstColumn As Long, iRow As long, iColumn As Long
firstRow = rng1.Rows(1).Row - 1
firstColumn = rng1.Columns(1).Column - 1
Set overlapRng = rng1.Offset(rng1.Rows.Count).Resize(1,1)
For Each cell in rng1.SpecialCells(xlCellTypeConstants)
iRow = cell.Row - firstRow
IColumn = cell.Column - firstColumn
If rng2(iRow, iColumn).Value = cell.Value Then Set overlapRng = Union(overlapRng, cell)
Next
Set overlapRng = Intersect(overlapRng, rng1)
CheckRangesOverlap2 = Not overlapRng Is Nothing
End Function
你可以在巡演中使用" Main"功能如下:
Sub Main()
Dim loopset As Worksheet
Set loopset = WorkSheets("myLoopsetSheet")
With loopset
Set rngA = .range("A2-A999")
Set rngB = .range("B2-B999")
Dim overlaps As Long
If CheckRangesOverlap1(rngA, rngB, overlaps) Then
' your code to handle overlaps number
End If
Dim overlapRng As Range
If CheckRangesOverlap2(rngA, rngB, overlapRng) Then
' your code to handle overlapRng range
End If
End Sub