I have a cell range that I am selecting one single cell from, removing the cell from the range, and then selecting another random cell. This loop is performed a total of 6 times.
Upon the completion of each loop both Range.Count and Range.Address reflect the removal, but while the loop is running, it will continue to potentially select removed cells. I use the cell removal function elsewhere and it performs as expected.
If both the count and the addresses for the range are showing the removal, why are those removed cells being selected? What am I doing wrong?
Code is as follows:
someRange = RangeToString(namesList)
MsgBox someRange
someDate = namesSheet.Range("F12").Value
For i = 1 To 3
For j = 1 To 2
For k = 1 To namesList.Count
Set randomName = GetRandomName(namesList)
MsgBox randomName & " was selected for date " & someDate & " and the size of the range is: " & namesList.Count
available = AvailabilityCheck(randomName, someDate )
If available = True Then
If i = 1 And j = 1 Then
namesSheet.Cells(18, "E").Value = randomName
ElseIf i = 1 And j = 2 Then
namesSheet.Cells(19, "E").Value = randomName
ElseIf i = 2 And j = 1 Then
namesSheet.Cells(18, "I").Value = randomName
ElseIf i = 2 And j = 2 Then
namesSheet.Cells(19, "I").Value = randomName
ElseIf i = 3 And j = 1 Then
namesSheet.Cells(18, "K").Value = randomName
ElseIf i = 3 And j = 2 Then
namesSheet.Cells(19, "K").Value = randomName
End If
Set namesList = ExcludeCell(namesList, genSheet.Range(randomName.Address))
namesString = RangeToString(namesList)
MsgBox namesList.Address
Exit For
End If
Next k
Next j
If i = 1 Then
someDate = namesSheet.Range("J12").Value
Else
someDate = namesSheet.Range("L12").Value
End If
Next i
Set FooFunction = namesList
And the function to remove the cells is:
Function ExcludeCell(ByVal rngMain As Range, rngExc As Range) As Range
Dim rngTemp As Range
Dim RNG As Range
Set rngTemp = rngMain
Set rngMain = Nothing
For Each RNG In rngTemp
If RNG.Address <> rngExc.Address Then
If rngMain Is Nothing Then
Set rngMain = RNG
Else
Set rngMain = Union(rngMain, RNG)
End If
End If
Next
Set ExcludeCell = rngMain
End Function