How to fix MS Access Form Combobox error in VBA - arrays

I originally had my combobox cbSortOrder defined in the form as a fixed Value List. I am now attempting to set this in VBA code, using an array. I have tried with a variant and string array but do not think my issue is connected with that but is something to do with the combobox definition.
When attempting to set these values in a With statement, I get the Object Doesn't Support Method error.
I have attached screenprints of the actual error and properties of my combobox.

Unfortunately, you cannot use collections as row source in Access. A Row Source Type of Value List refers to a comma (or semicolon) separated text (depends on the list separator setting in Windows).
If you don't want to use such a value list, use a Row Source Type of Table/Query and specify a table or query name. You can also insert a SELECT statement directly into this field.
This also means, that you must store the entries in a table for this Row Source Type. You can also use a local table instead of a table in the back-end.
Also, the ComboBox has no List property. Use the RowSource property instead. In the code behind of the form you can omit the Forms("formName") part.
With cbSortOrder
.RowSourceType = "Table/Query"
.RowSource = "SELECT Id, Description FROM tlkpSortOrder ORDER BY Description"
End With
or
With cbSortOrder
.ColumnCount = 2 ' If you have and id and a text
.ColumnWidths = "0" ' Hides the Id column
.RowSourceType = "Value List"
.RowSource = "1,Ascending,2,Descending,3,Undefined"
End With
See also: ComboBox.RowSourceType property (Access)

Related

Set Value to a Report Textbox from a Query

I made a query that only shows me a single field and a single record from another query, how can I put that value in a textbox in a report?
The record I want to set is a date that I insert with a MsgBox.
I read that there are ways to just put in the Control Source "=[table]![field]" but I get the Name? error, another way I read but did not understand it is defining a recordset. I can't put the value to the textbox despite trying the ways I've read in other posts.
One simple way is with DLookup() domain aggregate function expression in textbox. If field name has space or punctuation/special characters or is a reserved word, [ ] delimiters will be required. Usually table/query name does not but can't hurt.
=DLookup("[fieldname]","[tableORquery name]")

Handling Nulls from database table

I am displaying a database table on a datagridview (Winform) and I have noticed that all the null values of the table have converted on the datagridview to something that resembles blank spaces.
If I check the value of the cell is Null the statement turns false
dgv.Rows(r).Cells("Fld").Value Is Nothing = True
If I query the length of the string within the cell I get an error (so these may not be blank spaces).
Ideally I would like to avoid the conversion (have on the datagridview all the nulls from the database table). Is there a way I can stop the conversion?
If this is not possible, how can I identify what those cells now hold?
null and nothing are two differenet things...
The keyword Nothing is used to specify or assign that a var of reference type is not pointing anything, no object is instantiated for this var.
while DBNull.Value is an object used to point out that a type of a field of the db is of null value.
hereyou need to use dbnull...
The values in your cells are System.DBNull.
You can test for them using the IsDBNull method.
For example:
If IsDBNull(dgv.Rows(r).Cells("Fld").Value) Then
' Do Something
End If

Can I reference a field by name using a variable?

I can get a value from a .net data table that has columns named "Col1" and "Col2" like this:
DataTable dt = new DataTable()
// some more code that fills it
Console.Writeline("{0}, {1}", dt.Rows[0]["Col1"], dt.Rows[0]["Col2"]);
I could also use a variable if my datatable has a lot of columns
string x = // something that will be one of the columns in the table
dt.Rows[i][x] = "Some new value"
Is anything like this possible in NAV with a Record variable?
Well "like" this but not exactly. You can use RecordRef type to get reference to a field. But to interact with the certain field you will still need to adress it by its field number. You can iterate through all fields in the table and check their names to find the one you need. Not performant though.

DLookUp behavior in Form_Current with Label Captions

Access 2010 here.
Ok, Dlookups appear behave different based on where they are used. I have this Dlookup
inside a ClockNo_AferUpdate() subroutine that works well on new form entries to change a label's caption to what is found in the "Employees" DB under "EmployeeName" field based on the entered "ClockNo" in a ClockNo combo-box:
Me.LabelName1.Caption = DLookup("[EmployeeName]", "Employees", "[ClockNo] =" & Forms![InspectionEntryForm]!ClockNo)
The Employees database has four fields: AutoNumber-type "ID," Number-type "ClockNo," Text-type "Shift," and Text-type "EmployeeName."
Re-EDIT:
The RowSource for the ClockNo combo box as it sources from the Employees database:
SELECT DISTINCTROW [ClockNo], [EmployeeName] FROM [Employees] ORDER BY [ClockNo];
END Re-EDIT
What I am looking for is the same functionality in Form_Current() so browsing through older entries preserves the Label's caption based on the entered ClockNo. Unfortunately, simply re-using the above Dlookup gives a "Run-time error '3075': Syntax error (missing operator) in query expression '[ClockNo] ='."
Attaching the Dlookup as a control source to a text box does work O.K, but labels seem to be the best use here. I have mucked about with the Criteria section of the Dloopkup for some time without any real success.
End goal is to have a simple label next to a combo box that displays the employee's name based on their current and past ClockNo entries. The name is stored in a separate Employees database alongside their clock number and their shift.
This should be quite simple as both the ClockNo entry and the Label operate on the same form with the same database. Thanks for your input!
You have a combo box named ClockNo with this as its Row Source:
SELECT DISTINCTROW [ClockNo], [EmployeeName]
FROM [Employees]
ORDER BY [ClockNo];
I'm not sure why you want DISTINCTROW there. I would have suspected DISTINCT to be more appropriate. But I don't think it matters.
The important point is that the combo already includes [EmployeeName], so you shouldn't need to use DLookup to fetch [EmployeeName] again. Simply read the value from the second column of the combo's selected row.
Imagine your form includes a text box named txtEmployeeName. In the form's current event, you could do this:
Me.txtEmployeeName = Me.ClockNo.Column(1)
Notice the column index numbers start with 0, so the second column is .Column(1).
And you could do the same thing in the combo's After Update event.
Finally, you wanted to change a label's .Caption, but I showed you how to change a text box's .Value. If you can't make this technique work with the label, just use a text box instead. You can set the text box's Enabled property to No and adjust its other properties so that it is visually indistinguishable from a label.
Another approach could be simpler still. If you want to keep [ClockNo] as the combo's bound value, but are willing to display [EmployeeName] as the combo's selected value, you can set the width of the first column ([ClockNo]) to zero. You would still see both [ClockNo] and [EmployeeName] in the dropdown. If this is acceptable, you wouldn't need to bother with a label or text box.

Copy data from lookup column with multiple values to new record Access 2007

I am copying a record from one table to another in Access 2007. I iterate through each field in the current record and copy that value to the new table. It works fine until I get to my lookup column field that allows multiple values. The name of the lookup column is "Favorite Sports" and the user can select multiple values from a dropdown list.
I believe the values of a multivalued field are stored in an array but I cannot access the values in VBA code! I've tried myRecordset.Fields("myFieldName").Value(index) but it didn't work. I don't understand how Access stores multiple values in one field.
I saw something about ItemsSelected on another forum but I don't know what Object is associated with that method.
Thanks for any help!
I would recommend against using multivalue fields for precisely the reason you're running into, because it's extremely complex to refer to the data stored in this simple-to-use UI element (and it's for UI that it's made available, even though it's created in the table design).
From your mention of "ItemsSelected," you seem to be assuming that you access the data in a multivalue field the same way you would in a multiselect listbox on a form. This is not correct. Instead, you have to work with it via a DAO recordset. The documentation for working with multivalue fiels explains how to do it in code, something like this:
Dim rsMyField As DAO.Recordset
Set rsMyField = Me.Recordset("MyField").Value
rsChild.MoveFirst
Do Until rsChild.EOF
Debug.Print rsChild!Value.Value
rsChild.MoveNext
Loop
rsChild.Close
Set rsChild = Nothing
Now, given that you can usually access the properties of a recordset object through its default collections, you'd expect that Me.Recordset("MyField").Value would be returning a recordset object that is navigable through the default collection of a recordset, which is the fields collection. You'd think you could do this:
Me.Recordset("MyField").Value!Value.Value
This should work because the recordset returned is a one-column recordset with the column name "Value" and you'd be asking for the value of that column.
There are two problems with this:
it doesn't actually work. This means that Me.Recordset("MyField").Value is not reallly a full-fledged recordset object the way, say, CurrentDB.OpenRecordset("MyTable") would be. This is demonstrable by trying to return the Recordcount of this recordset:
Me.Recordset("MyField").Value.Recordcount
That causes an error, so that means that what's being returned is not really a standard recordset object.
even if it did work, you'd have no way to navigate the collection of records -- all you'd ever be able to get would be the data from the first selected value in your multivalued field. This is because there is no way in this shortcut one-line form to navigate to a particular record in any recordset that you're referring to in that fashion. A recordset is not like a listbox where you can access both rows and columns, with .ItemData(0).Column(1), which would return the 2nd column of the first row of the listbox.
So, the only way to do this is via navigating the child DAO recordset, as in the code sample above (modelled on that in the cited MSDN article).
Now, you could easily write a wrapper function to deal with this. Something like this seems to work:
Public Function ReturnMVByIndex(ctl As Control, intIndex As Integer) As Variant
Dim rsValues As DAO.Recordset
Dim lngCount As Long
Dim intRecord As Integer
Set rsValues = ctl.Parent.Recordset(ctl.ControlSource).Value
rsValues.MoveLast
lngCount = rsValues.RecordCount
If intIndex > lngCount - 1 Then
MsgBox "The requested index exceeds the number of selected values."
GoTo exitRoutine
End If
rsValues.MoveFirst
Do Until rsValues.EOF
If intRecord = intIndex Then
ReturnMVByIndex = rsValues(0).Value
Exit Do
End If
intRecord = intRecord + 1
rsValues.MoveNext
Loop
exitRoutine:
rsValues.Close
Set rsValues = Nothing
Exit Function
End Function
Using that model, you could also write code to concatenate the values into a list, or return the count of values (so you could call that first in order to avoid the error message when your index exceeded the number of values).
As cool as all of this is, and as nice as the UI that's presented happens to be (it would be really nice if they'd added selection checkboxes as a type for a multiselect listbox), I'd still recommend against using it precisely because it's so much trouble to work with. This just takes the problem of the standard lookup field (see The Evils of Lookup Fields in Tables) and makes things even worse. Requiring DAO code to get values out of these fields is a pretty severe hurdle to overcome with a UI element that is supposed to make things easier for power users, seems to me.
For a quick and dirty way of getting the values out of a multivalued ('complex data') column, you can use an ADO Connection with the Jet OLEDB:Support Complex Data connection property set to False e.g. the connection string should look something like this:
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\dbs\TestANSI92.accdb;
Jet OLEDB:Engine Type=6;
Jet OLEDB:Support Complex Data=False
The multivaled type column will now be of type MEMO (adLongVarWChar) with each value separated by a semicolon ; character.
But that's only half the problem. How to get data into a multivalued column?
The Access Team seem to have neglected to enhance the Access Database Engine SQL syntax to accommodate multivalued types. The 'semicolon delimiter' trick doesn't work in reverse e.g.
INSERT INTO TestComplexData (ID, weekday_names_multivalued)
VALUES (5, 'Tue;Thu;Sat');
fails with the error, "Cannot perform this operation", ditto when trying to update via ADO recordset :(

Resources