Why can't I get properties from members of this collection? - vba

I've added some form controls to a collection and can retrieve their properties when I refer to the members by index.
However, when I try to use any properties by referencing members of the collection I see a 'Could not set the ControlSource property. Member not found.' error in the Locals window.
Here is a simplified version of the code:
'Add controls to collection'
For x = 0 To UBound(tabs)
activeTabs.Add Item:=Form.MultiPage.Pages(Val(tabs(x, 1))), _
key:=Form.MultiPage.Pages(Val(tabs(x, 1))).Caption
Next x
'Check name using collection index'
For x = 0 To UBound(tabs)
Debug.Print "Tab name from index: " & activeTabs(x + 1).Caption
Next x
'Check name using collection members'
For Each formTab In activeTabs
Debug.Print "Tab name from collection: " & formTab.Caption
Next formTab
The results in the Immediate window are:
Tab name from index: Caption1
Tab name from index: Caption2
Tab name from collection:
Tab name from collection:
Why does one method work and the other fail?
This is in a standard code module, but I have similar code working just fine from within form modules. Could this have anything to do with it?
Edited to add
formTab was declared as a Control, but I find that if it is declared as an Object then the code works.
This will probably solve my problem, but in the interests of furthering my knowledge I would be grateful for any explanation of this behaviour, particularly with regard to the difference in running the code in the different types of module.

This is a really great question. Your edit at the end of the post reveals a lot about how VBA works and what's going on here. I'm not 100% this what's going on, but I'll explain what I think is happening.
A Collection in VBA (and VB6, for that matter; same code base) is not strongly typed. This means that everything in a collection is technically an "object." In the .NET world (as of .NET 2.0), it's possible to have strongly typed collections so that you could say "everything in this collection is a Control object." In VBA, this isn't possible with a Collection.
In your first iteration, where you are referring to the item indexed in the activeTabs collection, activeTabs(x + 1) is referring to an object. When you tell VBA to look up .Caption of that object, it doesn't know what the underlying type is (I think), so it has to simply look to see if the underlying object type contains a property or method called Caption. As you can see, Tab controls do in fact contain a property called Caption.
In your second interation, where you are doing a For Each loop, I think the problem is that the Control type probably doesn't have a property called Caption, though different types of controls probably do. For example, a text box control probably doesn't have a Caption property whereas as label control does have a Caption property.
You have a few options to fix your second loop. 1) You could declare formTab as a Tab control (I'm not sure exactly what it's called). The Tab control should have a Caption property. 2) If every control in activeTabs is not specifically a Tab control (in which case, you should probably call it activeControls instead of activeTabs), you could check within your loop to see if the formTab is actually a Tab control. If it is, cast it as a Tab control and then call .Caption. Until you cast it as a Tab control, VBA won't know that it has a Caption property since a regular Control object doesn't have a caption property.
In the end, you can get away with using objects as in your first loop and letting the runtime figure out what to do, but that can give really bad performance. In general, it's better to work with your specific types in a strongly-typed language. It also helps to show in your code that you know specifically what you're working with rather than leaving it to the runtime to decide what properties and methods you can work with.

Related

Get the name and properties of controls dynamically

I have 10 TrackBar1 TrackBar2, TrackBar3 ..... TrackBar10. What I want is how to manipulate it.
I Have problem with access to TrackBar control property Min, Max, Value ....
For i = 1 to 10
' its OK
Me.Controls("TrackBar" & i.ToString("0")).Text = "Test1"
' Error -Min is not a member "System.Windows.Forms.Control"
Me.Controls("TrackBar" & i.ToString("0")).Min = 10
Next
When you index the Controls collection, you get a Control reference back. That collection can store any type of control, so the only thing that they all have in common is that they inherit the Control class. That means that you can access any members of the Control class directly. Text is a member of the Control class so you can access the Text property directly. Any members that are more specific than that require a cast as the more specific type in order to access them. If you want to access members of the TrackBar class then you need a reference of type TrackBar rather than type Control, which means casting as that type.
Dim c = Me.Controls("TrackBar" & i)
Dim t = DirectCast(c, TrackBar)
To explain casting, I always use the example of taking a pet to the vet. A vet can treat all types of animals but, when you take your pet, it is a specific type of animal. When you present a box to the vet, all they know is that there's an animal inside, so all they know that they can do for it is the things that apply to all animals. Once you take your pet out of the box and they see what type of animal it is, they then know that they can do all the things specific to that type of animal. Your pet didn't magically change from one type to another but the vet now knows all the specific things it can do for it as well as the general.
That's how casting in programming works. Your TrackBar was always a TrackBar but, because it was initially accessed via a Control reference, the compiler only knew that it can do things with it that are common to all controls. The cast informs the compiler of the specific type so the compiler knows that it can do things with it specific to that type.
One option to avoid the explicit cast is to just get the TrackBars in the first place:
For Each tb In Me.Controls.OfType(Of TrackBar)()
'Use tb here.
Next
The OfType method will filter out all items not of the specified type and will return references of the specified type, so tb is type TrackBar in that code. You'd have to use a For Each loop in this case, so you have less control over the order the items are accessed. They will be returned in accordance with the z-order on the form. That means that if you added them in ascending numerical order, which seems likely, and did not change the z-order, you'll still get them back in ascending numerical order.

Change access form properties from a function

I'm trying to move the OnClick code from one of the buttons on a form to a function, but I'm having some issues. The button in question, called "Reset", changes the properties of most of the objects on the form. Stuff like:
Me.btnName.Caption = "Caption"
Me.btnName.Visible = True
Me.btnName.Top = 123
Me.btnName.Height = 456
'Etc
When moving this over to a function I can't seem to get this to work. I've tried a few different ways of writing it that I found while searching around, but none of them seem to work. I'm messing with some objects in the main form and some in the subform, so I'll show a few examples of both. Edited to include error messages
Forms("FormName").btnName.Caption = "Caption"
'Application-defined or Object-defined error
Forms("FormName").Controls("btnName").Caption = "Caption"
'Ms Access cannot find the referanced form (I've double and triple checked that it is correct)
Forms("FormName").SubFormName.Form.btnName.Caption = "Caption"
'Application-defined or Object-defined error
Forms!FormName!btnName.Caption = "Caption"
'Cannot find the referenced form
Forms!FormName!SubFormName!btnName.Caption = "Caption"
'Cannot find the field reffered to in your expression
Forms!FormName.Controls!btnName.Caption = "Caption"
'Cannot find the referanced form
Forms!FormName!SubFormName!Form.btnName.Caption = "Caption"
'MS Access can't find the field 'SubFormName'
No matter what I try of these I can't seem to get it to work. Maybe I'm just doing something simple wrong, or maybe you can't change properties like this from a function. Regardless, if anyone knows, I would appreciate the help.
Note that the function I'm trying to use is in a separate module, not in the code behind the form.
So you have a OnClick handler on some form's code-behind, responsible for assigning a bunch of properties for objects that live on that form.
What you have done is called encapsulation: outside code doesn't need to care about the Top and Height properties (and others) of the form's btnName button - truth is, outside code shouldn't even need to care that there's a button on the form.
So you're taking this nicely encapsulated object, and moving code around for no apparent reason.
If you need that functionality to be invoked from the outside, then yes, move it out of the OnClick handler.. but not outside the form's code-behind.
Move it to some Public Sub OnReset() procedure, and if outside code needs to invoke that logic, then have it call theForm.OnReset.
Private Sub ResetButton_Click()
OnReset
End Sub
Public Sub OnReset()
Me.btnName.Caption = "Caption"
Me.btnName.Visible = True
Me.btnName.Top = 123
Me.btnName.Height = 456
'Etc
End sub
That way you leave the implementation details of the form within the form itself, while giving outside code an abstraction to say "I don't care what your buttons are named; I don't care what size they are or what their captions are - but when I say 'Reset', you shall re-initialize whatever values you've got for them" - outside code doesn't need to know what Reset does specifically.
Put it this way: the day you rename that btnName button, would you rather need to simply adjust the form's code-behind, or hunt down every possible place in the entire project that could possibly be changing that button's Caption or whatever other property value?
FYI Foo!Bar.Something is late-bound code, shorthand for Foo.Item("Bar").Something: neither Bar nor Something are validated at compile-time. Contrast with Me.btnName.Whatever, where a typo is immediately picked up by the compiler: early-bound code that the compiler is able to validate should always be preferred.
You need to set the property to something:
Forms!FormName!btnName.Caption = "New Caption"
or, if on a subform:
Forms!FormName!<NameOfSubformCONTROL>.Form!btnName.Caption = "New Caption"

Is there a way to consolidate iteration through form controls for different activities

I just started rewriting an application from vba (Access) to vb.net + SQLServer so not very experienced in .net.
I am creating custom controls (Form + form controls) with a number of extra properties PrevValue, Modified (similar then the one of Textbox), Dirty, DirtyEnabled, SQLColumnName, SQLTableName to enable AutoUpdating and undoing in my forms the form exposes IsDirty, Initialising and Isready properties and an undo method.
Doing so it occurs that I have to write 3 times the same iteration code in different places:
For each Ctrl as Control in frm.Controls ' frm being a reference to the form
if typeOf Ctrl is MyTextBox
with DirectCast(Ctrl, MyTextBox)
' here comes the variable code depending what needs to be done
end with
elseif TypeOf Ctrl is MyComboBox
' etc.... for MyListBox, MyCheckBox etc....
I also have a number of custom controls MyNumBox and MyDateBox that inherit from MyTextBox but with some modified behavior (Formula evaluation, date manipulation, calendar...) how do I avoid doing an extra test on them.
One version of this Iteration is in the SQLProcessClass where the modified controls are added as SQLParameter and after iteration calling the SQLProcessClass Update or Insert, but ... after successful SQL activity I need to iterate through the controles again to reset the modified flag for each control. Elsewhere I need it to implement a form undo to reset all the controls to their previous values.
It seems to me I have two options
1. repeating that iteration code everywhere I need to iterate through the forms controls. I don't like it as every time I would need to create a new custom control I have to add some lines X times in different modules/classes ... very bad programming
2. Creating one form iteration procedure containing all the different activities that normally belong to another class within that "centralised" procedure, that could be better then (1) but I don't like it that much either.
Is there a better way of doing it using some .net functionality I don't master yet ?
Thanks for any advise.
Iterating through from controls can be tricky since controls are often nested. A more controlled approach would be to add another collection object to your form where you keep references to your added controls.....
e.g
Dim My_Widgets as New List(of Your-Control-Class-Name)
Then when you create the controls to the form also add them to that list.
My_Widgets.Add(Widget_Object)
After that it is a simple matter to iterate through that list.
For Each Widget as My_Widget_CLass in My_Widgets
' do what you need to do to Widget
Next
If you need to reference individual controls directly, use a dictionary object instead..
e.g.
Dim My_Named_Widgets as new Dictionary(of String, Your-Control-Class-Name)
Then add your control references to the dictionary by name
My_Named_WIdgets.add("<Whatever_You_USe_To_Identify_It>", Widget_Object)
You can then reference the specific control by the ID or name
My_Names_Widgets("ID").Property = Whatever '... etc
You seem to be indicating you have other controls for other purposes, as such it would be prudent to create similar collections for each type.

Can I find out if an AppleScript object has a certain property?

I'm attempting to script BBEdit to make me feel more at home in coming from TextMate. One thing I need to be able to do is see if an object I have a reference to has a particular property.
For instance:
tell application "BBEdit"
tell front window
get selected items
end tell
end tell
This will succeed on a project window, but not on a disk browser window, because the latter does not have a 'selected items' property. How do I see if there is such a property in the object?
Please note: I know how to inspect an object in Script Editor (get properties) to see what properties it has, but I need to know at runtime what they are.
What about the class?
tell application "BBEdit"
if class of window 1 is disk browser window then
# ...
else
# ...
end if
end tell
I don't have bbedit so I can't check, but if different types of windows exist, and each type of window has different properties, then can't you just check the window type first? Then you would know what type of properties you can get. There must be some basic property of a window that tells you its type or kind or whatever that would help you make the decision.
The only solution I have so far is to wrap it in an error handler:
try
set sel to selected items
on error errMsg number errNum
if errNum is -1700 then
-- Code that handles no selected items attribute
return
end
error errMsg number errNum
end try
-- Code that handles when selected items attribute exists
There is a difference between documents and windows in BBEdit. Windows are an element of documents, but only windows have the selection property, so you can check the type of window first and avoid catching errors entirely (and make for cleaner code as a result).
Also, try using the selection property, which is hard property in BBEdit as opposed to "selected items" because selection will always return a usable object, even if only an insertion point.

How would one detect a property of type "InvalidOperationException" within a collection?

Consider the following vb.net code for an office add-in (for access):
td = db.TableDefs(objectName)
For Each fld In td.Fields
For Each fldprp In fld.Properties
Debug.Print(fldprp.Value.ToString())
Next
Next
the variable "db" is a .net representation of the access vba return result from "Application.CurrentDB()". "td" is of type "DAO.TableDefClass".
This code throws an exception of type "InvalidOperationException" when the value of the fldprp.value property cannot be determined (in Visual Studio, it shows the value as {"Invalid Operation."} in the watch window). fldprp.name, however, is available.
There are only a few properties which this occurs on. I'd like to be able to loop through all the fld.properties and output the values, but ONLY if it is not an exception.
I am pretty sure why it is happening (certain properties are not available in this context). What I need to know is how to detect this at run-time so i can skip the property.
I can't seem to find a solution that will work. Help would be greatly appreciated.
Inside the body of the inner loop, put this at the top:
If TypeOf fldprp Is InvalidOperationException Then Continue
http://msdn.microsoft.com/en-us/library/0ec5kw18%28VS.80%29.aspx
I don't know your specific situation, but what I would suggest is using an explicit filter for the object types you want to include instead of filtering out the ones you don't want to include.