OKay, I figured it out.
Following the part in the macro where you set the new reference to the local variable value, the variable value needs to be set to 'Null'. Otherwise, everytime the lookup fails and there's no value which corresponds to the old reference the macro just input the variables...