How to Pass Multivalued field in query to VBA function - vba

In my project I have a table1 that has an ID and a text field. table2 has a multi-valued field multifield wherein I can select multiple values from table (via lookup).
Now, I have query1 where I want to pull the value from multifield - not multifield.value and pass it to a VBA function, like this: IDsToNames: table2.multifield. Problem is that VBA gives me this error:
The multi-valued field 'table2.multifield` is not valied in the expression IDsToNames(table2.multifield)
Now, I've tried with IDsToNames([table2].[multifield]) with the same results.
Here is my query's SQL:
SELECT table2.Title, table2.multifield, IDstoNames(table2.multifield) AS FieldNames
FROM table2;
If I remove the IDsToNames function from the SQL, then table2.multifield by itself will return the IDs like: 5, 4, 1 properly. I'm trying to fetch the second column of table1 instead of the first one that includes the IDs. So i figured I'd try passing that field to a function and perform a string split and them look them up with dlookup in a loop. But I can't get the field data into the function.
Is there a way to do this?

Is there a way to pass a multivalued field directly to a VBA function from within an SQL statement? No, regrettably.
However, there are various alternative methods that you can implement to get the list of values stored in the field. It's easy to ramble on about the pros and cons of Access multivalued fields. I'm not going to do that in detail, but it is worth stating that the primary benefit of a multivalue field is the convenience and apparent simplicity of the Access interface being able to automatically list and allow selection of multiple values of a one-to-many relationship. Trying to mimic that behavior in Access can be very awkward and cumbersome (and often impossible). Much of the implementation details for the multivalued fields are "hidden" (i.e. not well documented or are not exposed to the standard SQL or VBA programming interfaces). This includes the ability to pass the mutlivalued field to a VBA function from within an SQL statement. Regardless of how intuitive the intended behavior seems, Access will not simply pass the same concatenated list of values that it displays to another function. But there are still times when one simply wants the list of values, made accessible in a simple list. The information linked to by Gustav is useful and should be well understood for querying multivalued fields, but it still does not address other perfectly reasonable actions required for multiple values. Hopefully the following pointers are useful.
If the values are needed within a standard SQL statement, I suggest passing the primary key value(s) to a VBA function. Then have the VBA function look up the record and retrieve the multivalued-field values using DAO recordsets.
Because this will call the VBA function for every row, this can be (very) slow. It is possible to optimize the function using various techniques, like opening a static recordset object. Further details are beyond the scope of this answer.
Since you're already in code at this point and can structure VBA and queries however you want, the most efficient query will circumvent the multivalued-field itself and use standard SQL joins to get what you need. For instance, if you want to get all of the related user names, then open and enumerate the following recordset to build your list of names:
sSQL = "SELECT table2.key, table2.multifield.value, UserTable.Username " & _
" FROM UserTable INNER JOIN table2 ON UserTable.ID = table2.multifield.Value" & _
" WHERE (table2.key = [KeyParameter])"
Set qry = CurrentDb.CreateQueryDef(, sSQL)
qry.Parameters("KeyParameter") = keyPassedToFunction
Set rs = qry.OpenRecordset
If the SQL query can/will be opened as a DAO recordset in a code context and you still need to retrieve the multivalued-field as a single field, there is a way to enumerate the multivalued-field in VBA.
If the code ends up repeatedly opening and closing multiple recordsets, especially in multiple nested loops, it is likely that you could improve efficiency by restructuring the SQL using appropriate joins and changing the data processing order.
Rant: As you might notice, it is somewhat inconsistent that the underlying recordset object of an SQL statement does indeed return an object which can be enumerated in code, although the Access SQL engine refuses to pass such an object to a VBA function. The SQL engine already deals with boxing and unboxing data into the VBA variant type, so it seems reasonable that when implementing the multivalue fields, they could have had the SQL engine simply box the multivalued recordset object and passed it to a VBA function to be handled similar to the following code... so the original attempt in the question was not unreasonable.
The following code snippet illustrates that the multivalue field is returned as a DAO.Field object containing a DAO.Recordset2 object:
Dim rs as Recordset2
Set rs = CurrentDB.OpenRecordset("SELECT table2.multifield ... FROM ...")
Dim sList As String
sList = ""
If TypeOf rs![multifield] Is Recordset2 Then
Dim rsMVF As Recordset2
Set rsMVF = rs![multifield]
Dim bFirst As Boolean
bFirst = True
rsMVF.MoveFirst
Do Until rsMVF.EOF
If bFirst Then
sList = rsMVF.Fields(0)
bFirst = False
Else
sList = sList & "," & rs.Fields(0)
End If
rsMVF.MoveNext
Loop
'* DO NOT CLOSE the Recordset based on the Multivalue field.
'* Access will close it automatically.
End If
'* sList will contain comma-separated list of values

Related

MS Access Table (and TableDef) Properties

A table in MS Access opened in Design View exposes several properties, as does the table's Property Sheet. Many of these properties are undocumented or documented only for other objects. The question is, to which object do these properties belong? Further, how does one identify them in code? Pressing F1 for context help in each case reveals no clues.
Examples include (and recognize that the names below follow from their visual context, not an object model):
Field.Description is a column in Design View (along with Field Name and Data Type) but is undocumented. Also, iterating DAO.Field.Properties reveals no Description field and references to the property fail.
Table.Description appears in the Property Sheet but also is undocumented.
Table.Filter and Table.OrderBy and their ~OnLoad counterparts appear on the Property Sheet but are documented only for other objects. I understand that information specified here is intended somehow to flow through to forms for which the table is the RecordSource, but the mechanism is not obvious and still leaves the initial question, flowing through from which object's property.
Table.LinkChildFields and Table.LinkMasterFields appear in the Property Sheet but are documented only for other objects. Also, their use in this context is not obvious.
Other table properties on the Property Sheet tell the same tale.
Any thoughts, in general or specific to any of the foregoing, would be most helpful and appreciated.
To show properties of some Access database object (table, query, form, report, ...), we can do this on VBA, defining this global function:
Function objShowProperties(ByVal xobj As Object)
Dim i As Long, varPropValue, prop As Object
On Error Resume Next
'
' loop over properties:
'
i = 0
For Each prop In xobj.Properties
varPropValue = prop.Value
'
' sometimes we have error accessing property value:
'
If (Err <> 0) Then
varPropValue = "[UNAVAILABLE]"
Err.Clear
End If
Debug.Print prop.Name, "=", varPropValue
i = i + 1
Next
On Error GoTo 0
Set prop = Nothing
objShowProperties = i
End Function
In my Acccess db I've a table named customers.
To show properties of this table, I call the above function like this:
objShowProperties CurrentDb.TableDefs("customers")
In my debug console, I got this:
All listed properties can then be accessed directly on VBA code, eg, RecordCount property:
dim lngRecords as long
lngRecords = CurrentDb.TableDefs("customers").Properties("RecordCount")
Hope this will help you.
A few things:
Field.Description is a column in Design View (along with Field Name and Data Type) but is undocumented.
No, it is not un-documented.
You are confusing DAO, and that of ms-access.
DAO "field" does not have a description property. So, it not un-documented at all.
Also in Access, there is help. You an put your cursor in the description, and hit help, and you get this:
so, place cursor here, and hit f1 for help:
And now you get this:
So, you are confusing the database engine object called DAO.FIELD with that of ms-access and it allowing you to have/enjoy/see a description in the table desinger.
I should point out that the DAO object model does not have a table designer!!!
In fact, what Access does is add's a custom property to the field, and then display's that. So, field.Description is not un-document, it in fact does not exist.
As noted in the other post here, you can "interate" all of the properties. However, if you use the database engine outside of ms-access, and EVEN create fields in code (or even by sql commands), you WILL STILL find that no descripton property exists. However, as noted, there is this thing called help, and you can give help a try, as it will explain what the description setting in ms-access does.
However, at the end of the day, field.description is not un-documented, and in fact does not exist.
so, if you read/look at/see documentaiton for the DAO field object, then these properties and options will not be found.
After all, you might be using c++, c# or some other system and that database engine that MS-Access just also happens to use.
MS-Access is not the database here. It is a tool that lets you build software, and forms and reports, and write code.
When you using MS-Access, you are not required to use the JET (now called ACE) database engine to store your data. You are free to use the Oracle database, or SQL server or whatever.
So, features of Access and things like link master fields etc.?
Those are MS-Access features, and not the database engine (ACE) features.

Can we format, in VBA, a query field properties after it is create?

In Access, when creating a new query using vba, some of the data I'm getting are currency, but it comes by default as General Number. I would like to change it's format like we can do in the Property Sheet, but I can't seem to find a way.
I have tried
db.QueryDefs("TestQuery").Fields("SumOfSomething").Type = DAO.dbCurrency
But then I get: Run-time error '3219': Invalid operation.
I have searched around a bit and found a similar question (but couldn't find it back) to which the answer was that you can't change that after it is created. I fail to see the point of having the possibility to change the type if we can't actually do it.
So, in the end, can we change (in VBA) the properties of a field after the query is created?
Your question appears to be simple, but as you've probably guessed by now, it isn't.
The format property is a custom property of a field. They can be present, and if they are, they should be changed using the Field.Properties collection, but if they aren't, they need to be created using Field.CreateProperty method and then appended to the Fields.Properties collection
Const currencyFormat As String = "€ #,##0.00;€ #,##0.00-"'Dutch currency format, you need to set this for your locale
Dim qd As DAO.QueryDef
Set qd = CurrentDb.QueryDefs("TestQuery")
On Error Resume Next
qd.Fields("SumOfSomething").Properties!Format = currencyFormat
If Err.Number = 3270 Then 'Property not found, field had no format set
qd.Fields("SumOfSomething").Properties.Append qd.Fields("SumOfSomething").CreateProperty("Format", dbText, currencyFormat)
End If
On Error GoTo 0
You can get the currency format for your locale by setting a field to use it, and then using ?CurrentDb.QueryDefs("TestQuery").Fields("SumOfSomething").Properties!Format
We have to be clear here on the goal. Do you want to “just” cast or change the column type returned in a query, or do you want to modify the actual column type in the database table? These are two VERY different goals.
To use code to modify a column type, you have to create (add) the new column type, transfer the data, and then delete the old column, and then re-name the column back to the old type.
In other words, you can’t just change the data type, since Access will THEN have to update each and every row to the new data type.
The UI system in fact does the above behind the scenes.
If you use DAO code, then you need the following code outlined here:
http://accessblog.net/2007/03/how-to-change-field-type-using-dao.html
However, above is quite a bit of code. In place of DAO code to add the column, you CAN use a DDL command.
(SQL data definition language) to modify the type. Thus in code you can do this:
Dim db As dao.Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "ALTER TABLE dbo_tblHotels1 ALTER COLUMN MyAmount currency"
db.Execute strSQL, dbFailOnError
So in above, we change the column "MyAmount" to currency type.

MS Access - SQL append query behavior is erratic

I've been working on an Access database for the last couple weeks, and it's my first project with the tool. Dealing with append queries seems to have become an utter nightmare, and is incredibly frustrating. Even more so because it seems to have simply stopped working in any consistent manner overnight.
The SQL query that I have written goes thus:
PARAMETERS noteDetails LongText, noteTime DateTime, srcUserID Long;
INSERT INTO tblNotes (NOTE_DETAILS, NOTE_TIME_CREATED, NOTE_SOURCE_USER)
VALUES (noteDetails, noteTime, srcUserID)
In tblNotes:
NOTE_ID is an AutoNumber
NOTE_DETAILS is a Long Text
NOTE_TIME_CREATED is a Date/Time
NOTE_SOURCE_USER is a Number
The way that I'm running this query is through VBA:
Set qdf = CurrentDb.QueryDefs("qerApndNote")
qdf.Parameters(0).Value = txtDetails.Value
qdf.Parameters(1).Value = Now()
qdf.Parameters(2).Value = getCurrentUserID()
qdf.Execute dbFailOnError
qdf.Close
Set qdf = Nothing
' Where CurrUserID is a global long
' txtDetails.Value is a textbox's contents
' Now() is the VBA built-in function to return a date/time combo
I have attempted to run this query manually from the navigation bar, and it works fine when done in that manner.
However, running it from VBA has resulted in such things as there being no time / date inserted, sometimes a user ID is not inserted, sometimes both, sometimes even the details text is missing.
What is it that I'm missing? Is there any general advice for users of MS Access to follow that I am not? I'm aware that NOTE is a restricted word in Access, but I really don't think that should apply here, right?
Thanks in advance!
EDIT: The form that I'm passing data from is called frmNewNote, and there is a control in it named txtDetails. It's just a regular textbox. Don't really know what else to share about that.
The getCurrentUserID function is in a module, modGlobal:
Public CurrUserID As Long
Public Function getCurrentUserID() As Long
getCurrentUserID = CurrUserID
End Function
Public Function setCurrentUserID(CurrID As Long)
CurrUserID = CurrID
End Function
It's about as barebones as you can get, really. And there is never a circumstance that you'll get to the form before SetCurrentUserID has been called during your... session? There's a login form involved.
#Andre's code for logging:
0 noteDetailsText This is a note test
1 noteTimeCreated 9/6/2017 10:28:45 AM
2 srcUserID 1
As for my architecture, um, it's just the single database file right now, on the desktop. The entire function/sub is run when you click a button, btnEnter. It does some other stuff before it gets to the SQL statement bit - checks for null values and prompts user for entries if that's the case.
I just remembered something:
MS Access 2013 calling insert queries from VBA with strange errors
You have a LongText parameter. These don't really work. See also https://stackoverflow.com/a/37052403/3820271
If the entered notes will always be <= 255 characters, change the parameter to ShortText.
If the text can be longer, you'll have to use either SunKnight0's approach with a concatenated INSERT statement.
Or use a Recordset and its .AddNew method, which will be a similar amount of code to your current solution, but also be completely safe from injection or formatting issues.
You are doing way more work than you have to. All you need is:
DoCmd.RunSQL("INSERT INTO tblNotes (NOTE_DETAILS, NOTE_TIME_CREATED, NOTE_SOURCE_USER) VALUES ('" & Me.txtDetails & "',Now()," & CurrUserID & ")")
Note the change from txtDetails.Value to Me.txtDetails which is what may have been messing you up. This of course assumes the code runs in the form's context, otherwise you have to get he value of the text field using a reference to the form.
The only other thing to consider is making sure Me.txtDetails does not have any single quotes, so probably use Replace(Me.txtDetails,"'","''") instead.
That way you can also replace DoCmd.RunSQL with MsgBox to troubleshoot the exact query.

Microsoft Access VBA: need to get sql representation programmatically from existing query

I need to be able to get the sql "property" from an existing query. So for example I could define strRS as:
strRS = Me.RecordSource '.RecordSource returns the name of a query
Then pass that value to as yet undefined function UnknownFunction(strRS) that takes strRS as a value:
strSQL = UnknownFunction(strRS)
Then the desired output, strSQL would be the original SQL string that defines the query pointed to by the form's "RecordSource" property.
The closest I've been able to get is that there may be a solution using QueryDef, but that is for queries made on the fly? What should the UnknownFunction be?
Once I have the strSQL string then I can extract from it to make a related query.
Ok, it is trivial IF one doesn't make it too complicated. I probably was getting the wrong answer at first because I was confusing "QueryDefs" with "QueryDef", which I should have known.
So without further ado, the full working code is:
Function FCN_QClip(strQRY As String) As String
qds = CurrentDb.QueryDefs(strQRY).SQL
FCN_QClip = qds
End Function
?FCN_QClip("QueryName") will yield the desired result in the immediate window for an existing query. Thanks to Nathan.
The solution may also be found at Social MSDN.

Access VBA with custom function in SQL

I need to open a query or recordset or something (datasheet view) with some sql i build in my vba based on form control values. I have a "many to many" relationship in my data (kind of). Pretend we have a Person table, a Pet table and an ID Pet_Person table. I want to have a list of my People with a concatenated string of all their pets in one row of returned data. So....
Row Person Pets
1 Kim Lucius, Frodo, Cricket, Nemo
2 Bob Taco
And I googled and I found you can write functions in the VBA to be called from the SQL. So. Here's the problem. I have a lot of records and once opened, I cannot move around the datasheet view/query/whatever without that concatenation function being called everytime I click on a row. I only need it called once when the sql is initially ran... like a snapshot or something.
I'm not too well versed with Access and the possibilities. I've tried some things I found online that all had the same result... that concatenation function being called when I touched that resulting dataset at all.
Last thing I tried looks something like:
With db
Set qdf = .CreateQueryDef("Search Results", q)
DoCmd.OpenQuery "Search Results", , acReadOnly
.QueryDefs.Delete "Search Results"
End With
StackOverflow really never formats my stuff correctly. Probably user error.... oh, well.
Edit:
Oh Bart S. Thank you but you went away too soon for me to understand the answer if it is there. Thank you.
Oh Remou. Yes, I saw your post. I used your post. I've used many of your posts while working on this project. Why access doesn't support all SQL functions I am so used to with MySQL I have no idea. You're a great addition to this site. I should have linked to it with my question but the coffee hadn't kicked in yet.
I have my concatenation function and I am calling it within the sql. I was opening it with the docmd to open that recorset or query or whatever. But here is my issue (and I may be creating this myself by trying too many solutions at once or I might be overlooking something)... it keeps calling that function each time I touch the resulting dataset/query/thing and there's too much data for that to be happening; I am seeing the hourglass simply too much. I am positive this is because of the way I am opening it. This is intended to be the result of a search form screen thing. I'm thinking I need to just literally make another form in access and populate it with my resulting recordset. I think that is what you guys are telling me. I'm not sure. This is a weird example. But... you know with Excel, when you write an inline function of some kind to get some value for each row... and then you do a copy and paste special for just values (so not the function)... I need that. Because this function (not in Excel, obviously) must query and that takes to long to reapply each time a row is clicked on (I think it's actually requerying each row if a single row is clicked on, almost like it's rerunning the sql or something). Like the NIN/Depeche Mode song Dead Souls... It keeps calling me/it.
Here are a few thoughts and strategies for coping with the issue of constant data re-loading:
Make sure your query is set to snapshot. Same for the form.
This of course makes the data read-only, but it may help a bit.
Cache the result of your query into a local table, then show/bind that table instead of the query itself.
This will make the user wait a bit longer initially while the query is executed and saved into the local table, but it makes the interface much smoother afterwards since all data is local and doesn't need to be re-calculated.
Create a local table localPetResult (on the client side) that has all the fields matching those of the query.
Instead of binding the query itself to the datasheet form, bind the localPetResult to it, then in the form's VBA module handle the OnLoad event:
Private Sub Form_Load()
' Remove all previous data from the local cache table '
CurrentDb().Execute "DELETE FROM localPetResult"
' Define the original query '
Dim q as String
q = q & "SELECT Row, "
q = q & " Person, "
q = q & " Coalesce(""SELECT PetName FROM Pets WHERE Person='"" & [Person] & ""',"","") AS PetNames "
q = q & "FROM MyData"
' Wrap the query to insert its results into the local table '
q = "INSERT INTO localPetResult " & q
' Execute the query to cache the data '
CurrentDb().Execute q
End Sub
One you have it working, you can improve on this in many ways to make it nicer (freeze the screen and display the hourglass, dynamically bind the ersult table to the form after the data has been calculated, etc)
Cache the result of each call to the coalescing function.
I've used that to calculate the concatenation once for each record, then store the result in a Dictionary whose key is the ID of the record. Subsequent calculations for the same ID are just pulled from the Dictionary instead of re-calculated.
For instance, add the following to a VBA module. I'll assume that you use Remou's Coalesce function as well.
Option Compare Database
Option Explicit
' A Scripting.Dictionary object we'll use for caching '
Private dicCache As Object
' Call to initialise/reset the cache before/after using it '
Public Sub ResetCoalesceCache()
If Not (dicCache Is Nothing) Then
dicCache.RemoveAll
End If
End Sub
' Does the Same as Coalesce() from Remou, but attempts to '
' cache the result for faster retrieval later '
Public Function Coalesce2(key As Variant, _
sql As String, _
sep As String, _
ParamArray NameList() As Variant) As Variant
' Create the cache if it hasn't been initialised before '
If dicCache Is Nothing Then
Set dicCache = CreateObject("Scripting.Dictionary")
End If
If IsNull(key) Then
' The key is invalid, just run the normal coalesce '
Coalesce2 = Coalesce(sql, sep, NameList)
ElseIf dicCache.Exists(key) Then
' Hurray, the key exists in the cache! '
Coalesce2 = dicCache(key)
Else
' We need to calculate and then cache the data '
Coalesce2 = Coalesce(sql, sep, NameList)
dicCache.Add(key, Coalesce2)
End If
End Function
Then, to use it in your query:
' first clear the cache to make sure it doesn't contain old '
' data that could be returned by mistake '
ResetCoalesceCache
' Define the original query '
Dim q as String
q = q & "SELECT Row, "
q = q & " Person, "
q = q & " Coalesce2([Row], ""SELECT PetName FROM Pets WHERE Person='"" & [Person] & ""',"","") AS PetNames "
q = q & "FROM MyData"
' Bind to your form or whatever '
...
I always do it like this:
Dim strSql As String
strSql = "SELECT * FROM table WHERE field=something;"
Set rs = CurrentDb.OpenRecordSet(strSql)
Then use RS to perform actions. There may be better ways. You can, for example, create a query directly in Access and call it from VBA.
While looping the recordset, you can concatenate the string:
Dim strResult As String
While (Not rs.EOF)
strResult = strResult & rs!yourfield
WEnd