You cannot Always omit “Value” (1 Viewer)

Uncle Gizmo

Nifty Access Guy
Staff member
Local time
Today, 15:49
Joined
Jul 9, 2003
Messages
16,244
Often people are advised they do not need to refer to a Control's Value implicitly like this:-

Code:
Dim strValue As String
strValue = cboCurrent.Value

This advice is given because "Value" is the default, therefore it is unnecessary to append it, So you could write the above like this:-

Code:
Dim strValue As String
strValue = cboCurrent

However this is not entirely true in Every case!

I noticed this “Unexpected behaviour” a few years back, when I tried to convert one of the Northwind database’s macro’s into a VBA routine. Some of the Northwind macros save information into TempVars. The conversion routine used the combobox name only, omitting the Value property and resulted in an Error.

I would guess it's not widely known that by omitting the “Value” property when saving to TempVars causes the TempVar to assume you are trying to save an object to it, as most VBA programmers avoid useTempVars, and would seldom experience this problem.

You can reproduce this behaviour yourself:-
Try and add the value of a combobox to a TempVar with this Code:-

Code:
TempVars.Add "CurrentUserID", cboCurrent

You will trigger the following error:-

Code:
Error 32538 ---  TempVars can only store data. They cannot store Objects.

This is because the TempVar thinks you are trying to assign an object to it (the combobox) and not the value of the object (the combobox Value).

There is a Video providing a bit more information on my website here:-


There is a Video explaining how to download the northwind sample database here:- TempVars Value Error - Nifty Access



What’s interesting is, if you assign the combobox value to a string variable, (you can do this without appending the control name with the “Value” property)

then you assign the string variable to the TempVar and it works fine:-

Code:
Private Sub Command0_Click()
Dim strValue As String

strValue = cboCurrent

MsgBox " >>> " & strValue

TempVars.Add "CurrentUserID", strValue
End Sub


Useful thread on TempVars and macros here :- TempVar in Form Issues... NO VBA
 

NauticalGent

Ignore List Poster Boy
Local time
Today, 11:49
Joined
Apr 27, 2015
Messages
6,281
Good info Tony. I can’t recall the details but I have experienced the same behavior from time to time myself without TempVars. Because of this I ALWAYS use .Value just to eliminate that possibility.

With regards to TempVars, I really don’t know how it got implanted in my head to avoid them and I have never taken the time to learn about them. One thing is for sure: SOMEBODY managed to convince me to avoid them!
 

Users who are viewing this thread

Top Bottom