473,771 Members | 2,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A Dlookup alternative that will return all values in a string/array

7 New Member
Hi

After a lot of research I didn't manage to solve the following problem:

I have a table called 'Autos' with fields [ID], [Owner], [Car]

1 ¦ Mike ¦ BMW
2 ¦ Mike ¦ Ford
3 ¦ Mike ¦ Toyota
4 ¦ Nick ¦ Audi
5 ¦ Nick ¦ Ford
7 ¦ Anna ¦ Honda

I want to be able to get the table 'AllCars' with fields [Owner], [Cars]:

Mike ¦ BMW Ford Toyota
Nick ¦ Audi Ford
Anna ¦ Honda


If I use VBA's Dlookup/DFirst/DLast I am only going to get a single value. How can I get all of them? I could use queries and/or VBA and we can assume that the Autos table is always sorted by the Owner. I don't want to use a crosstab query because it will limit the number of column headings.

I want to use the results in a report that will say "Mike now owns BMW Ford Toyota cars." I think this is something very useful and common and there must be an easy way to do it.

If you don't know the answer to this please just give me an alternative to the Dlookup function that will return an array/string of all the values, and I will experiment myself.

Thanks in advance!
Feb 22 '07 #1
7 6829
Michael R
176 New Member
1st step:

Create a Crosstab query using Cross Tab Query wizard, with [Owner] for row heading and [Car] for column headings. Use [Id] with Count function for number to be calculated for each row and column intersection. Disable include sums.

Now view the query. You have each owners as rows and cars as columns, pretty neat heh?

Here's the SQL, in case you'll have trouble:
TRANSFORM Count(Autos.ID) AS CountOfID
SELECT Autos.Owner
FROM Autos
GROUP BY Autos.Owner
PIVOT Autos.Car;

2nd step: Add the following Function to your project (not form) module:
Expand|Select|Wrap|Line Numbers
  1. Function HasCars(strOwner As String) As Variant
  2.  
  3.     Dim db As Database
  4.     Dim fld As Field
  5.     Dim blnIsNull As Boolean
  6.     Set db = CurrentDb
  7.     For Each fld In db.QueryDefs!Autos_Crosstab.Fields
  8.          If fld.Name <> "Owner" Then
  9.             If IsNull(DLookup(fld.Name, "Autos_Crosstab", "[Owner] = '" & strOwner & "'")) Then _
  10.                 Flag1 = True
  11.             If blnIsNull = False Then _
  12.                 If (DLookup(fld.Name, "Autos_Crosstab", "[Owner] = '" & strOwner & "'")) Then _
  13.                 HasCars = HasCars & fld.Name & ", "
  14.           End If
  15.     Next fld
  16.     'cleans the output string
  17.     If Right(HasCars, 1) = Chr(32) Then HasCars = Left(HasCars, Len(HasCars) - 2)
  18. End Function
Save.

3rd step:

Now create a new query that selects distinct car names and utilizes the HasCars function we've created:

SELECT DISTINCT Autos.Owner, HasCars([Owner]) AS HasCars
FROM Autos;

That's all. The function however, can be simplified and improoved by accesing only to the relevant fields using some sort of index, but I'm not much knowladgabe in RecordSet programming. Maybe someone else could simplify it.
Feb 23 '07 #2
Michael R
176 New Member
Note: the crosstab query name should be: Autos_Crosstab
Feb 23 '07 #3
Michael R
176 New Member
Addition: In case some owner names might be entered as "Name ", for the HasCars to be calculated without extra commas you can replace this code:
Expand|Select|Wrap|Line Numbers
  1. 'cleans the output string
  2.     If Right(HasCars, 1) = Chr(32) Then HasCars = Left(HasCars, Len(HasCars) - 2)
with this one:
Expand|Select|Wrap|Line Numbers
  1. 'cleans the output string
  2.     If Right(HasCars, 2) = "," & Chr(32) Then HasCars = Left(HasCars, Len(HasCars) - 2)
Feb 23 '07 #4
supertsik
7 New Member
Thanks very much for your reply.

Unfortunately, I have thought about using your method, but as I mentioned in my question I cannot use crosstab queries simply because the column headings I need are 792! As you understand, Cars table was just a simple example. My real problem is not cars, it's the 792 construction areas for the venues of the Olympic games.

It's very bizarre that you cannot create a query in a simple way that will group your answers in a single field separated by commas. As you can use COUNT, SUM and all the other aggregate functions in SQL, a CSV function would be really useful. It seems to me that lots of people would want to do something like that.

If you, or anybody else has any better ideas I would really appreciate them!
Feb 23 '07 #5
NeoPa
32,573 Recognized Expert Moderator MVP
Thanks very much for your reply.

Unfortunately, I have thought about using your method, but as I mentioned in my question I cannot use crosstab queries simply because the column headings I need are 792! As you understand, Cars table was just a simple example. My real problem is not cars, it's the 792 construction areas for the venues of the Olympic games.

It's very bizarre that you cannot create a query in a simple way that will group your answers in a single field separated by commas. As you can use COUNT, SUM and all the other aggregate functions in SQL, a CSV function would be really useful. It seems to me that lots of people would want to do something like that.

If you, or anybody else has any better ideas I would really appreciate them!
Why people continually seem to expect this to be a natural concept in either SQL or any RDBMS is entirely beyond me. This and numbering lines in a query, both entirely foreign to SQL concepts.
However, if you need it there is something that can approximate to what you need (Combining Rows-Opposite of Union ).
Let me know if you have any trouble getting it to work in your environment.
Feb 26 '07 #6
ADezii
8,834 Recognized Expert Expert
Hi

After a lot of research I didn't manage to solve the following problem:

I have a table called 'Autos' with fields [ID], [Owner], [Car]

1 ¦ Mike ¦ BMW
2 ¦ Mike ¦ Ford
3 ¦ Mike ¦ Toyota
4 ¦ Nick ¦ Audi
5 ¦ Nick ¦ Ford
7 ¦ Anna ¦ Honda

I want to be able to get the table 'AllCars' with fields [Owner], [Cars]:

Mike ¦ BMW Ford Toyota
Nick ¦ Audi Ford
Anna ¦ Honda


If I use VBA's Dlookup/DFirst/DLast I am only going to get a single value. How can I get all of them? I could use queries and/or VBA and we can assume that the Autos table is always sorted by the Owner. I don't want to use a crosstab query because it will limit the number of column headings.

I want to use the results in a report that will say "Mike now owns BMW Ford Toyota cars." I think this is something very useful and common and there must be an easy way to do it.

If you don't know the answer to this please just give me an alternative to the Dlookup function that will return an array/string of all the values, and I will experiment myself.

Thanks in advance!
It took a little thought, but here is code which will accomplish exactly what you want without the use of a Crosstab Query:
__1 Create a Query called qryUniqueValues . This Query will contain only the [Owner] Field from the Autos Table in Ascending Order. It will also have its Unique Values property set to Yes. This will establish an ascending list of 'Unique' Owners.
__2 Create the AllCars Table with 2 Fields [Owner] (Text 50) and [Cars] (Memo). All the Data will be Appended to this Table: a Unique Owner to the [Owner] Field, and a comma-delimited list of all cars that the [Owner] has will be appended to the [Cars] Field.
__3 Run the following code from wherever you so desire. If you have any other questions, feel free to ask.
Expand|Select|Wrap|Line Numbers
  1. Dim MyDB As DAO.Database, MyRS As DAO.Recordset
  2. Dim RSAutos As DAO.Recordset, strCars As String
  3. Dim RSAllCars As DAO.Recordset
  4.  
  5. Set MyDB = CurrentDb()
  6. Set MyRS = MyDB.OpenRecordset("qryUniqueOwners", dbOpenDynaset)
  7. Set RSAutos = MyDB.OpenRecordset("Autos", dbOpenDynaset)
  8. Set RSAllCars = MyDB.OpenRecordset("AllCars", dbOpenDynaset)
  9.  
  10. Do While Not MyRS.EOF
  11.   Do While Not RSAutos.EOF
  12.     If MyRS![Owner] = RSAutos![Owner] Then
  13.       strCars = strCars & RSAutos![Car] & ","
  14.     End If
  15.     RSAutos.MoveNext
  16.   Loop
  17.     With RSAllCars
  18.       .AddNew
  19.          RSAllCars![Owner] = MyRS![Owner]
  20.          RSAllCars![Cars] = Left$(strCars, Len(strCars) - 1)
  21.       .Update
  22.     End With
  23.   strCars = vbNullString
  24.   RSAutos.MoveFirst
  25.   MyRS.MoveNext
  26. Loop
  27.  
  28. MyRS.Close
  29. RSAutos.Close
  30. RSAllCars.Close
Sample Output (the AllCars Table), after single execution:
Expand|Select|Wrap|Line Numbers
  1. Owner    Cars
  2.  
  3. Anna    Honda
  4. Mike    BMW,Ford,Toyota
  5. Nick    Audi,Ford
  6. Pete    Cadillac,Porsche,Lamborghini,Presada,Saturn
Feb 26 '07 #7
supertsik
7 New Member
Thanks A Lot!!! It Really Helps!!!
Mar 2 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3330
by: john | last post by:
Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value for my first element but my subsequent printf's will return garbage. Can someone let me know what I am doing wrong. Thanks in advance. -jlewis
16
2651
by: collinm | last post by:
hi i would like to return a string char *readFile(char *tmp_dir_led, char *directory, char *filename) { FILE *fp; char line; snprintf(tmp_mnt_dir_led, sizeof(tmp_mnt_dir_led),"%s/%s",
8
13948
by: Jeff Johnson | last post by:
Hi, I've begun converting an ASP site over to .NET and I'm a novice at both the new platform as well as C#. I have a COM+ object that returns a string array when it is called. The size of the array can vary depending on the parameters passed. What I need to do is loop through the returned array and if applicable write the array element to the screen.
2
3643
by: Bnc119 | last post by:
Hello, I have written a C# COM server that has a few methods and a property called DataItems that returns an ArrayList. During the course of execution the ArrayList gets populated with several strings. I am having issues retrieving these strings from my C++ client. My C# code looks like this: public object DataItems { get
1
1154
by: moondaddy | last post by:
I need to return a nested string array from a function and am getting hung up on syntax. Here's a simple example of a function that returns the array and how I'm trying to call it. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim arr()() As String = Me.TestArr1 End Sub Private Function TestArr1() As String
3
4332
by: XML newbie: Urgent pls help! | last post by:
Does anyone have a snippet of code that will convert a string array to a long array? I've nearly smashed my head against the wall trying to figure this out. I'm Using vb.net 2005 Pls reply asap. I thaanku all in advance. God bless u. Pls reply with code.
8
71613
by: Pim75 | last post by:
Hello, I'm defining a string array like: Dim strArray() As String = {"1", "2"} Can I add some values to this string array later in the code? It's not clear to me how to do this. I hope someone can help me. Thanks in advance!
1
1683
by: jef.d | last post by:
I am attempting to read through a text file & then update an HTML page table w/ the output from the text file (ie; statusing by table). What I want the code to do is read through the file, look for a line that matches a couple of strings, next is loop through the file from that match to 30 lines searching for a "score" from, then store that score; and then look for the next algorithm (8 of them) run & score. What I get is an array w/...
1
3654
by: Constantine AI | last post by:
Hi i am trying to get User input if data does not exist within a DLOOKUP table. I have gotten it to work for one record but not multiple, i have tried to incorporate my code into a loop procedure but i have failed. Could anyone give me any advice? Dim db As Database Dim rst As Recordset Dim rst2 As Recordset Dim strSQL As String Dim Widthval As Integer Dim Depthval As Integer Dim Heightval As Integer Dim...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10103
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9911
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.