VBA Access getting RowSource to find lookup values - ms-access

VBA noob here (as of this mourning),
In MS Access I wrote a test function to find the value of a record base on some criteria you pass in.
The function seems to work fine except in cases where there is a lookup in the column that I am searching.
Basically it might return "19" and 19 corresponds to some other table value.
It seems that the RowSource of the column is what Im after so I can do a second query to find the true value.
Can someone point me in the right direction on finding the RowSource assuming I know the column name and then utilizing it to find the value Im after?
Edit: It seems that Im not explaining myself clearly, Here is a picture of what I trying to get programatically

Try this -- I think I finally understand why you are looking for the RowSource -- sorry I didn't "get" it at first. The field you're trying to pull is a foreign key into a description table.
This function should work as a general solution for all such fields (assuming the RowSource always has the primary key first, and the description second). If there is no RowSource, it will just pull the value of the field.
It's based on your original code, rather than the changes proposed by #ron, but it should set you in the right direction. You should fix it to make it parameterized, and allow for variant data types, as ron suggests (+1 ron)
As an aside, use the ampersand (&) to join strings together in VBA to avoid things like this: abc = "1" + 1, where abc is now equal to 2 instead of "11" as you would expect if both items were intended to be strings.
Public Function lookUpColumnValue(Database As Database, column As String, table As String, lookUpColumn As String, lookUpValue As String) As String
Dim sql As String
Dim recordSet As DAO.recordSet
Dim result As String
lookUpColumnValue = "" 'Return a blank string if no result
On Error Resume Next
sql = "SELECT [" & table & "].[" & column & "] FROM [" & table & "] WHERE [" & table & "].[" & lookUpColumn & "] = '" & lookUpValue & "'"
Set recordSet = Database.OpenRecordset(sql)
If Not recordSet.EOF Then
Dim td As DAO.TableDef
'this gives your number - say, 19
result = recordSet(column)
Set td = Database.TableDefs(table)
'Get the rowsource
Dim p As DAO.Property
For Each p In td.Fields(column).Properties
If p.Name = "RowSource" Then
RowSource = Replace(td.Fields(column).Properties("RowSource"), ";", "")
Exit For
End If
Next
If Not RowSource = "" Then
Dim rs2 As DAO.recordSet
Dim qd As DAO.QueryDef
Set qd = Database.CreateQueryDef("", RowSource)
Set rs2 = Database.OpenRecordset(RowSource)
If rs2.EOF Then Exit Function
PKField = rs2.Fields(0).Name
rs2.Close
qd.Close
sql = "SELECT * FROM (" & RowSource & ") WHERE [" & PKField & "]=[KeyField?]"
Set qd = Database.CreateQueryDef("", sql)
qd.Parameters("KeyField?").Value = result
Set rs2 = qd.OpenRecordset()
If Not rs2.EOF Then
'NOTE: This assumes your RowSource *always* has ID first, description 2nd. This should usually be the case.
lookUpColumnValue = rs2.Fields(1)
End If
Else
'Return the field value if there is no RowSource
lookUpColumnValue = recordSet.Fields(column)
End If
End If
End Function

If I understand your question correctly, I think using a parameter query will solve your problem. Using parameters is good practice since they will perform implicit data type casts and also prevent injection attacks.
Notice in the following function, I changed the lookupValue to a Variant type, which allows you to pass any type of value to the function.
Public Function lookUpColumnValue( _
database As DAO.database, _
column As String, _
table As String, _
lookUpColumn As String, _
lookUpValue As Variant) As String
Dim sql As String
Dim recordSet As DAO.recordSet
Dim result As String
Dim qd As QueryDef
Set qd = database.CreateQueryDef("")
sql = "SELECT [" + table + "].[" + column + "] FROM [" + table + "] " & _
"WHERE [" + table + "].[" + lookUpColumn + "] = [parm1];"
qd.sql = sql
qd.Parameters![parm1] = lookUpValue
Set recordSet = qd.OpenRecordset()
result = recordSet(column)
EDIT
lookUpColumnValue = DLookup("Space Use Description", "Space Use Codes", result)
End Function

Related

Reading data types from a table and run Alter table statement without locking table

I am using the below function to determine the field data types from whichever table is given in the function parameter. Basically the function reads the data type from the table and compares it to what it should be based on the "FieldDataTypes" table. If it doesn't match, then I would like to run an Alter table SQL statement as shown below. However I am realizing that once I open the recordset I am unable to alter the table. When I run the Sub/Function below I get the error:
The database could not lock table "TEST TABLE" because it is already in use by another person or process. 3211.
How can I get around this so that I can loop through the fields and still alter the data types as necessary?
Thanks,
Charlie
Sub TestReFormat()
FncFormatFields ("TEST TABLE")
End Sub
Public Function FncFormatFields(strTableName As String)
Dim rst As DAO.Recordset
Dim fld As Field
Dim strFieldName As String
Dim strSQL As String
Dim intDataType As Integer
Dim intDataTypeCheck As Integer
On Error GoTo FormatFieldsErr:
rstSQL = "SELECT * FROM [" & strTableName & "]"
Set rst = CurrentDb.OpenRecordset(strTableName)
For Each fld In rst.Fields
strFieldName = fld.Name
intDataType = fld.Type
Debug.Print strFieldName & " " & intDataType
intDataTypeCheck = DLookup("DataTypeInt", "FieldDataTypes", "[FieldName] = '" & strFieldName & "'")
Debug.Print intDataTypeCheck
If intDataTypeCheck <> intDataType Then
strSQL = "ALTER TABLE [" & strTableName & "] ALTER COLUMN [" & strFieldName & "] " & intDataTypeCheck & ""
DoCmd.RunSQL (strSQL)
End If
Continue2428:
Next fld
Exit Function
FormatFieldsErr:
If Err.Number = 2428 Then
Resume Continue2428
Else
MsgBox Err.Description & " " & Err.Number
End If
End Function
Break your function into two parts:
A Function that examines the table returns a SQL array of ALTER TABLE statements
A Function that executes the SQL array
The query that locks the table in 1) will be closed, allowing you to alter it in 2) without error.
PS: Use rstSQL = "SELECT TOP 1 * FROM [" & strTableName & "]" so you don't waste resources returning multiple rows.
You can update data in a table without locking. In fact FEW know that the Access database engine JET/ACE can even update columns in records that are currently in use and dirty by other users (the update has to be specific to the one column - this is possible in some cases).
However, to modify a table structure and data type? You will require full exclusive rights and other users cannot have the table open, and you need full lock rights to the whole database.
Since in this case the data is of no interest, only the table structure, you can use a TableDef object to get the table structure; this will get around the lock:
Public Function FncFormatFields(tablename As String)
Dim dbs As Database, tdf As TableDef, fld As Field
On Error GoTo FormatFieldsErr:
Set dbs = CurrentDb
Set tdf = dbs.TableDefs(tablename)
For Each fld In tdf.Fields
Dim fieldname As String
fieldname = fld.Name
Dim datatype As Integer
datatype = fld.Type
Debug.Print fieldname & " " & datatype
Dim finalDatatype As Integer
finalDatatype = DLookup("DataTypeInt", "FieldDataTypes", "[FieldName] = '" & fieldname & "'")
Debug.Print finalDatatype
If datatype <> finalDatatype Then DoCmd.RunSQL "ALTER TABLE [" & tablename & "] ALTER COLUMN [" & fieldname & "] " & finalDatatype & ""
Next
Continue2428:
Next fld
Exit Function
FormatFieldsErr:
If Err.Number = 2428 Then Resume Continue2428
MsgBox Err.Description & " " & Err.Number
End Function
Even if the data is of interest, TableDef has an OpenRecordset method that returns the data in the table.
It might also be possible to use a snapshot-type recordset, which doesn't have an open connection to the database, and therefore shouldn't be affected by the lock. (I didn't test this.)
Note: I've only tested this with an .accdb; if this works as well with an .mdb that would be good to know.

VB6, MS Access, DAO - Display all records WHERE column-name IS NOT NULL

I need a bit of help with this, so what I am trying to do is to display all records WHERE column-name IS NOT NULL. What I have is:
Dim rs As Recordset
Dim sqlStr As String
Set WS = DBEngine.Workspaces(0)
DbFile = (App.Path & "\mydb.mdb")
strSql = "SELECT * FROM MyDatabaseName"
Set rs = db.OpenRecordset(strSql)
rs.MoveFirst
Do While Not rs.EOF
lblResult.Caption = ("cust Name: " & rs!SurName & " cust Surname: " & rs!FirstName)
rs.MoveNext
Loop
MsgBox ("End ")
What I have tried is
strSql = "SELECT * FROM MyDatabaseName WHERE column-name IS NOT NULL"
But I get an error 3131. Any help is appreciated. Also how can I display the result in a ListBox insted of Label.
Simple fix: enclose column names in square brackets when using special characters, like the - substraction operator:
strSql = "SELECT * FROM MyDatabaseName WHERE [column-name] IS NOT NULL"
The rest of your SQL seems valid.
If you want a list box with the results of this query as the list, just set its row source equal to this query, and set its row source type equal to Table/Query. No need for any VBA.
If you want to put everything in a label, use:
Do While Not rs.EOF
lblResult.Caption = lblResult.Caption & "cust Name: " & rs!SurName & " cust Surname: " & rs!FirstName & VbCrLf
rs.MoveNext
Loop

Display multiple specific records in a report

Let's say I have a single table called "Customers". It contains 2 fields:
Name
Address
I want users to be able to select multiple records by selecting their names. For example something like having a list box containing all the names of the records in the database. I want users to be able to select multiple items like:
Dave Richardson
Bob Smith
Sophie Parker
And then only display records with these names in the report.
You can use the WhereCondition option of the DoCmd.OpenReport Method to filter your report as needed.
Const cstrReport As String = "YourReportNameHere"
Dim custNames As String
Dim lItem As Variant
Dim strWhereCondition As String
With Me.yourListBoxName
For Each lItem In .ItemsSelected
custNames = custNames & ",'" & Replace(.ItemData(lItem), "'", "''") & "'"
Next
End With
If Len(custNames) > 0 Then
custNames = Mid(custNames, 2)
strWhereCondition = "[Name] IN (" & custNames & ")"
End If
DoCmd.OpenReport ReportName:=cstrReport, View:=acViewPreview, _
WhereCondition:=strWhereCondition
Note this approach has features in common with PaulFrancis' answer. In fact, I copied his code and modified it. The key difference is that this approach does not require you to revise a saved query in order to filter the report.
The setup I would I have is, a Form with a SubForm and a ListBox, the Listbox will have the names of all your customers. So the RowSource would be,
SELECT
customerNameFieldName
FROM
yourTableName;
The Multi Select property will be setup to Extended. Then a button will have the following code that will generate the SQL for the SubForm's recordsource.
Private Sub buttonName_Click()
Dim lItem As Varaint, strSQL As String
Dim custNames As String, whereStr As String
Dim dbObj As dao.Database
Dim tmpQryDef As QueryDef
Set dbObj = CurrentDb()
For Each lItem In Me.yourListBoxName.ItemsSelected
custNames = custNames & "'" & Me.yourListBoxName.ItemData(lItem) & "', "
Next
Id Len(custNames) <> 0 Then
custNames = Left(custNames, Len(custNames) - 2)
whereStr = "WHERE customerNameFieldName IN (" & custNames & ")"
End If
strSQL = "SELECT someFields FROM someTable " & whereStr
Set tmpQryDef = dbObj.QueryDefs("Summary 3 Q1")
tmpQryDef.SQL = strSQL
DoCmd.OpenReport "yourReportName", acViewNormal
Set dbObj = Nothing
Set tmpQryDef = Nothing
End Sub
So now the SubForm will have the RecordSource based on all the information you have selected in the ListBox.

Looping through an array and posting array to table

I am an old Foxpro programmer and I use to use arrays to post variable fields.
What I am trying to do is I have 15 date fields in the new table I designed.
In my query I have individual records with one date for activity.
I want to compile the 15 different dates for a each Client_id into one record with 15 dates but I can't seem to reference the table data as an array.
I have tried a couple different methods of defining the array but nothing seems to work.
Here is my code that I have. In my table I have 15 date fields named Mail_date1, Mail_date2, Mail_date3, etc.
I tried first defining it just as an array but did not like it; my code always fails when I try to reference the date field in the result table rs2!mdate2 = memdate(intcounter)
How can I reference my result table output fields as an array?
Do I have to put a whole bunch of if statements to load my results?
Seems like a waste.... should be able to load them as an array.
I am a new Access 2007 VBA programmer.
Dim db As DAO.Database
Set db = CurrentDb
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim FinTotal, intcounter As Integer
Dim FinMPU, FinVersion As String
Dim mail_date(1 To 15) As Date
Dim memdate(1 To 15) As Date
Dim mdate2 As String
Set rs1 = db.OpenRecordset( _
"SELECT NewFile.MPU_ID, " & _
" NewFile.MAIL_DATE," & _
" NewFile.TOTAL, " & _
" Freight.Version " &_
"FROM Freight " & _
" LEFT JOIN NewFile ON Freight.[MPU ID] = NewFile.MPU_ID " & _
"ORDER BY NewFile.MPU_ID, NewFile.MAIL_DATE")
Set rs2 = db.OpenRecordset("Final")
DoCmd.RunSQL "DELETE Final.* FROM Final;"
intcounter = 1
memdate(intcounter) = rs1!mail_date
FinMPU = rs1!mpu_ID
FinTotal = rs1!total
FinVersion = rs1!Version
rs1.MoveNext
On Error GoTo Error_MayCauseAnError
Do While Not rs1.EOF
Do While Not rs1.EOF _
And memdate(intcounter) <> rs1!mail_date _
And FinMPU = rs1!mpu_ID
intcounter = intcounter + 1
memdate(intcounter) = rs1!mail_date
FinTotal = FinTotal + rs1!total
FinVersion = rs1!Version
FinMPU = rs1!mpu_ID
rs1.MoveNext
Loop
If FinMPU <> rs1!mpu_ID Then
rs2.AddNew
mdate2 = "mail_date" & CStr(intcounter)
rs2!mdate2 = memdate(intcounter)
rs2!total = FinTotal
rs2!mpu_ID = FinMPU
rs2!Version = FinVersion
rs2.Update
FinTotal = rs1!total
FinVersion = rs1!Version
FinMPU = rs1!mpu_ID
intcounter = 1
memdate(intcounter) = rs1!mail_date
End If
rs1.MoveNext
Loop
first, if you expect and answer, you should really spend more time on properly formatting your explanation and your code...
Now, for some remarks and possible answer to the question:
You should DELETE FROM Final before you open that table in a recordset.
You should be explicit about the type of recordset you are opening:
' Open as Read-only '
Set rs1 = db.OpenRecordSet("...", dbOpenSnapshot)
' Open as Read/Write '
Set rs1 = db.OpenRecordSet("...", dbOpenDynaset)
You should Dim memdate(1 To 15) As Variant instead of Date as the Date datatype cannot be Null, and since you are pulling data from a LEFT JOIN, it's possible that the returned values could be Null if there are no corresponding data to Freight in the table Newfile.
That On Error GoTo Error_MayCauseAnError should probably not be there.
Use On Error Goto only to catch errors you can't deal with at all.
Using that here will only hide errors in your code. With some proper checks statements you should not even need the On Error Goto...
It looks like your first internal loop is trying to skip some records.
However, when that loop breaks, it could be because it reached EOF, and you never test for that in the code that follows the loop.
You never test if your intcounter goes beyond the 15 allocated dates.
Are you absolutely sure that you can never have more than 15 records?
You do not say which error message you get exactly. That could be useful to help determine the kind of issue at hand.
Instead of
mdate2 = "mail_date" & CStr(intcounter)
rs2!mdate2 = memdate(intcounter)
Use
rs2.Fields("mail_date" & intcounter).Value = memdate(intcounter)
the ! syntax of DAO really only is a shorthand for the longer rs.Fields("name") form.

A "Count" Based off Filters set in a Pivot Table

So, we have imported data which we have queried and then created a pivot table off that query. It is essentially a list of files, each having unique ID numbers, and various attributes (file extension, type of document, hash, etc). In any case, this data is based off "hits" on keyword searches from a different program. This means that there might be multiple records for the same Unique ID since there are multiple hits.
The pivot table allows us to illustrate/manipulate via filtering out certain criteria (e.g. we don't want certain file extensions or we don't want records with FIELD X or FIELD Y0. The report is fine, but we want to make a form/query/report/whatever that will pull a "count" (based off unique ID) which ignores duplicates. For example, once all the filters are set in the pivot table, based on the filters/output of the pivot table, we want something like this:
.PDF Files: 200 | total for field x | total field y | etc
.DOCX files: 320 | total for field x | total for field y | etc
Obviously, we want to ignore duplicates of the same Unique ID in the counts.
What is the best way to do this considering we will be manipulating the pivot table dynamically and often? The ideal scenario would to have the pivot table and another object (form/report/etc) open, and as the pivot table is manipulated whatever is displaying counts changes as well.
Here are some very rough notes notes. They are only minimally tested, and using IN would be a disaster with a lot of values, however, it would be easy enough to switch this round and use an excluded list. Perhaps you can get some ideas.
Dim oPTable ''PivotTable
Dim oPM ''PivotMember
Dim oFUpd ''PivotFilterUpdate
Dim oChildren ''ChildMembers
Dim fset ''FieldSet
Dim sWhere As String
Dim sTemp As String
Dim sSQL As String
Dim sDelim As String
Dim aStates As Variant
Dim i As Integer
Dim rs As DAO.Recordset
sDelim = """"
aStates = Array("Cleared", "Checked") ''Possible states
Set oPTable = Forms(0).PivotTable.ActiveView
sWhere = vbNullString
For Each fset In oPTable.FieldSets
sTemp = vbNullString
Set oChildren = oPTable.FieldSets(fset).Member.ChildMembers
For i = 0 To oChildren.Count - 1
Set oPM = oChildren(i)
Set oFUpd = oPM.Field.FieldSet.CreateFilterUpdate
If aStates(oFUpd.StateOf(oPM) - 1) = "Checked" Then
Select Case fset.BoundField.DataType
Case adChar, adLongVarWChar
sTemp = sTemp & "," & sDelim & oPM.Caption & sDelim
Case adInteger
sTemp = sTemp & "," & oPM.Caption
Case adDate
sTemp = sTemp & ",#" & oPM.Caption & "#"
Case Else
'' The above is a very short list.
'' Stop
End Select
End If
Next
If sTemp > vbNullString Then
sWhere = sWhere _
& " AND [" & fset.Name & "] IN ( " & Mid(sTemp, 2) & ")"
End If
Next
sSQL = "SELECT DISTINCT ID FROM [" & oPTable.Control.DataMemberCaption & "] "
sSQL = sSQL & "WHERE 1=1" & sWhere
Set rs = CurrentDb.OpenRecordset(sSQL)
MsgBox "Unique: " & rs.RecordCount
if that helps:
http://lazyvba.blogspot.com/2010/11/improve-your-pivot-table-to-count.html
it will get you the unique count of ID numbers by numbers you want, and you can still manipulate the pivot