Article ID: 107903
Article Last Modified on 10/10/2006
' In this macro, cellRange is an Object variable
' and cellItem is a Variant variable.
Sub loopTest()
Set cellRange = ActiveSheet.Range(Selection.Address)
' The following Concatenates an "A" to the default value of each
' cell.
For Each cellItem In cellRange
cellItem = cellItem & "A"
MsgBox cellItem
Next
' The cellRange will return the default value (not value&"A"), even
' though the loop above changed the value of the object.
For Each cellItem In cellRange
MsgBox "n = " & cellItem
Next
End Sub
The connection between the object and the variant is broken when the loop
attempts to write to the value property of the object. The result of this
break is that the new value is assigned to the Variant variable, but the
object is not updated. When the first loop references the variant, the
Variant variable passes the value that it is holding (instead of getting
the object's value property) and the loop appears to work. However, when
the second loop references the Variant variable, it is passed the value
that the variable is reading from the object--which was never changed.
163435 VBA: Programming Resources for Visual Basic for Applications
Additional query words: 8.0 XL
Keywords: kbdtacode kbprb kbprogramming KB107903