PDA

View Full Version : Detecting changes in a userform



RoyLiam
11-30-2006, 01:14 AM
Hi

I can't understand why the following does not detect when one of three fields had been changed, to validate a save function:

Private Sub UserForm_Initialize()
Dim changed As Boolean
changed = False
end sub

Private Sub code_Change()
changed = True
End Sub

Private Sub client_Change()
changed = True
End Sub

Private Sub path_Change()
changed = True
End Sub

Private Sub update_Click()

IF changed then

If code <> "" Then
Set oTemplate = Templates("O:\IT\code defaults.dot")
oTemplate.AutoTextEntries.Add code.Text & "|" & "client", Range:=Selection.Range
oTemplate.AutoTextEntries(code.Text & "|" & "client").Value = client.Text
oTemplate.AutoTextEntries.Add code.Text & "|" & "path", Range:=Selection.Range
oTemplate.AutoTextEntries(code.Text & "|" & "path").Value = path.Text
If oTemplate.Saved = False Then oTemplate.Save
MsgBox ("Client name and directory attached to client code")
Else
MsgBox ("There is no client code to attach client name and directory to")
End If
End If
End Sub



Why does 'changed' not become true and then allow the save?? Grateful for any ideas

thanks

TonyJollans
11-30-2006, 04:53 AM
Hi Roy,

Your changed variable is explicitly declared in the UserForm_Initialize procedure and exists only as long as that procedure is running.

In each of your other procedures a different variable, also called changed, is implicitly declared and exists only as long as the individual procedure is running.

Each of the variables is a different one. If you want to use the same variable across all the procedures you must declare it a higher level, the module level ...


Option Explicit

Dim changed As Boolean

Private Sub UserForm_Initialize()
changed = False
End Sub

' etc.


Note the Option Explicit line. This stops implicit declaration of variables and should normally be used. Had you had it in the first place you would have received compiler errors which might have helped guide you to the right solution. To have it automatically added to new modules, select Tools > Options from the VBE Menu and check the box for "Require Variable Declaration".

RoyLiam
11-30-2006, 12:27 PM
It now stores the value throughout the userform

appreciated

fumei
12-01-2006, 12:44 AM
Hi Roy, you should definitely follow Tony's suggestion and use Option Explicit. It will save you lots of headaches over the long run. It is strongly recommended.

Also, it will help if you look up and got a good grasp of Scope. Knowing how and where variables are used will increase the ability of your code to be efficient, and greatly aid in debugging.