PDA

View Full Version : Checking a checkbox when textBox1.Value changes



truszko1
05-27-2011, 08:36 AM
Hey,

I have search macro. There is a textbox in a userform, and a checkbox underneath. The 10 most recent searches are stored, and the most recent one appears in the textbox when a macro is run. By default, the checkbox is unchecked (titled: "Save as a new search string"). I have a piece of code that checks whenever a user changes the value in the textbox, and if the value changes, the checkbox gets checked (meaning, the new string will be saved).

Here is the code:


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

'textBoxValue is the value that appears in the textBox1 when a macro is run
If UserForm3.TextBox1.Value <> textBoxValue Then
CheckBox1.Value = 1
Else: CheckBox1.Value = 0
End If
...
End Sub


The problem is that the If statement is run before user changes the value in a textBox. It takes two changes for the checkBox to get checked. I don't understand why.
Any ideas?
Thanks!

Jay Freedman
05-28-2011, 08:52 AM
The various textbox events (KeyDown, KeyPress, character insertion, Change) always occur in that specific order. You picked a wrong one to do your test; the right one is the Change event, which occurs after the new character appears in the box.

truszko1
05-31-2011, 06:44 AM
Yup, it solved the problem. Thanks a lot!