![excel vba on keypress excel vba on keypress](https://wellsr.com/vba/assets/images/2017-01-20-UserForm-View-Code.png)
So now we have the answer: KeyAscii = 0 works because KeyAscii is an object and this sets the KeyAscii.Value property to 0. Sub TryToChangeObjectByRef(ByRef c As Class1) Sub TryToChangeObjectByVal(ByVal c As Class1) If it were passed ByRef then we’d be able to change the object reference itself: Module2 As Chip explains on his site, when an object is passed ByVal, we can’t change the reference to the object itself upstream – but we can change its properties. Sub TryToChangeProperty(ByVal c As Class1) Public Property Let MyValue(value As Long) The question now becomes: what happens when an object is passed ByVal? Let’s do a test with our own custom class: Class1
#Excel vba on keypress code#
This code is exactly the same but now KeyAscii looks more like an object (an instance of a class).
![excel vba on keypress excel vba on keypress](https://pratikmshah.github.io/img/posts/excel-vba/keypress.jpg)
I think things become clearer if we re-write the code so that it explicitly uses that Value property: If you look in the object browser you’ll see that it is a class and it has a default Value property. The most important point to this answer is that MSForms.ReturnInteger is not a literal: it looks like an Integer because it has Integer in the name – but it isn’t one. However, he knew from testing that, if he removed that line of code, the restricted entry was no longer enforced. KeyAscii is passed ByVal, so the change won’t propogate back to the caller of the event handler (incorrect).KeyAscii isn’t used at a later point in the procedure.The user thought that, in theory, that line of code should do nothing because: The question revolved around the highlighted line of code. I was posting on one of the online forums a while back and helped a user understand some code which he had found on the web and, in particular, how it restricted what could be typed into a textbox on a userform.