DLookup in Access not running until textBox clicked on in Form - sql

I'm setting 12 TextBox ControlSources in my Form from VBA using the following :
...
Me.Oct.ControlSource = "=DSum('GBPValue', 'MF YTD Actual Income & Adret', 'Month=10 AND Org_Type=[Key]')"
Me.Nov.ControlSource = "=DSum('GBPValue', 'MF YTD Actual Income & Adret', 'Month=11 AND Org_Type=[Key]')"
...
[Key] is the name of a textbox in the form
When the form loads up i get some odd behavior -
all of the summary form text boxes are blank as are all the dlookup text boxes
if i then click on one of the text boxes that has a dlookup control source assigned the summary text boxes for the other columns start to populate with 0's and #Num etc. and the dlookup runs and displays the expected numbers
once i've clicked on all the dlookup fields the summary numbers calc properly.
In the final version of this the query will be re-written after user clicks from the VBA so ... is this a sensible way to get the form to re-query the DB and, if so, how can i make the DLookups run/display automatically so that everything displays immediately on form load?

You are probably looking for Recalc (Me.Recalc). However, I suggest you use a recordset, rather than DlookUp, and the Current event for the form:
Dim rs As DAO.Recordset 'Needs MS DAO 3.x library
Dim db As Database
Dim strSQL As String
Set db = CurrentDb()
'Guessing that key is a form value
'Note that Month is a reserved word
strSQL = "SELECT [Month], Sum(GBPValue) As SumVal " _
& "FROM [MF YTD Actual Income & Adret] " _
& "WHERE Org_Type= " & Me.[Key]
& " GROUP BY [Month]"
Set rs=db.OpenRecordset(strSQL)
'You can probably use a Do While Loop, consider
'naming the controls, eg, Month10
rs.FindFirst "[Month]=10"
Me.Oct = rs!SumVal
'and so on

Related

How to count the sum of same data in access subform

I have two access subform.
First Subform (Pivot1234Subform)
1) First is (Pivot1234 subform). Its take pivot1234 table format. Then,this subform will show the data after user selection on listbox and dropdown text box. below are the code that generate this subform:
Generate PIvot1234 subform
Second subform (CountDuplicateSubform)
CountDuplicateSubform
this subform is follow query wizard duplicate data of pivot1234 table.
the purpose of this subform is to count the sum of data that containt same data in column FAMILY and WhichTest from pivot1234_subform after the summary in pivot1234 report is clicked.
example
if first row : family = a , whichtest =b
then second row : family =a , whichtest = b
it will appear in column third (count) "2"
example of the result
below are the code that i already try in Form_Load event:
{Private Sub Form_Load()
Dim strSQL As String
strSQL = "SELECT First(Pivot123_subform.Family) AS
[CountDuplicate_subform.Family], First(Pivot1234_subform.WhichTest) AS
[CountDuplicate_subform.WhichTest], Count(Pivot1234_subform.Family) AS
[CountDuplicate_subform.Count]" & _
"FROM Pivot1234_subform" & _
"GROUP BY Pivot1234_subform.Family, Pivot1234_subform.WhichTest" & _
"HAVING (((Count(Pivot1234_subform.Family))>1) AND
((Count(Pivot1234_subform.WhichTest))>1));"
Forms!CountDuplicate_subform.RecordSource = strSQL
Forms!CountDuplicate_subform.Form.Requery
End Sub

Changing headers display and order from a recordset to excel sheet

I have an excel sheet that I use as database, and a search form that allow user to search for information, based on some criterias, and display the filtered results in a new sheet.
I am using SQL to fetch data, and display them to the user.
I use something like top open connection, then to create a record set and pass my sql request to it
m_Connection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=Yes;"";"
Set OpenRecordset = CreateObject("ADODB.Recordset")
OpenRecordset.Open sql, GetConnection(), 3, 3, &H1
Set rst = OpenRecordset("SELECT * FROM [Database$] Where " & Myconditions & ";")
Everything works fine, but I need to allow users to choose the column headers names and order that may be different from what i have in the sheet from which i make my select that i call database
We need this because users are in different countries, so the display name will be configured based on the country of the user, but also we want to allow user to change the display name and order of the fields based on their needs and because the display name may be too long (multi line).
My real "database" sheet is about 110 columns, and about 1000 records (rows).
I can't publish the real data because it's confidential, but to help you understand me, I created this example that represent what I have
let us suppose I have this "database"
the user enter this search screen to select the information he needs from the database
I wish that the user will get this result and not in the same order and display of the database
as you can see, the display names and orders of the columns in the result page is different from the "database" sheet
I would like to create a configuration page, in which the user can specify the display name he wants and the order in which he wants the fields to appears. something like that
Is there any fast way to do that directly in my Recordset in SQL/EXCEL or I should after I fetch data, change the headers in excel sheet using vba ? if so, I have to make a kind of array in vba that contains both database Names and display names and replace the names of the database by its corresponding just before I show the result page shows ?
any suggestions ?
same question about the order of the fields, how to sort them based on the order the user choosed ? any fast way ?
Thanks for anyone who can help with the best way to do that
You could do the following, it loops through the data range based on the number of rows in the range being the min and max of positions available, it looks for these rankings in turn, in column C, then checks if shown, then add's the field name and it's alias to an array. This array is then joined. So using data similar to yours, in columns of the the same ordering, I called:
GenerateOrderedSQL("table 1",range("a2:d6"),3,4) A1:D1 contained headers
This called my function
Function GenerateOrderedSQL(strInputTable As String, _
rngRangeForSelection As Excel.Range, _
lngOrderColumn As Long, _
lngShowColumn As Long) As String
Dim l As Long
Dim fPos As Long
Dim lfPos As Long
Dim a() As Variant
l = rngRangeForSelection.Rows.Count
ReDim a(l)
For fPos = 1 To l
lfPos = Application.WorksheetFunction.Match(fPos, _
rngRangeForSelection.Columns(lngOrderColumn), 0)
If rngRangeForSelection.Cells(lfPos, lngShowColumn).Value = "Yes" Then
a(fPos-1) = "[" & rngRangeForSelection.Cells(lfPos, 1) & _
"] AS [" & rngRangeForSelection.Cells(lfPos, 2) & "]"
a(fPos-1) = a(fPos-1) & IIf(fPos < l, ",", vbNullString)
End If
Next
Debug.Print "SELECT " & Join(a, vbNullString) & " FROM [" & strInputTable; "]"
End Function`
This gave the following
SELECT [Fname] AS [First Name],[Lname] AS [Last Name],[Zip] AS [Zip],[City] AS [City] FROM [table 1]

How to access selected record column value in nested sub-datasheet form

I spend half day to figure out how to access value in nested datasheet form record.
Please, take a look at image below.
I have dblClick event on "SID" column cell. It's field name is "txtSID".
I need to grab that value (in picture "20") and pass it in VBA SQL.
There is some trick with datasheets. Looks like they has no control name or something.
Looks like I found solution. """ & Me![txtSID] & """ does the thing.
Private Sub txtSID_DblClick(Cancel As Integer)
Dim SQL As String
SQL = "INSERT INTO documents (stakeholder_id, document_type_id, status_id) VALUES (""" & Me![txtSID] & """, 1, 1);"
DoCmd.SetWarnings False
DoCmd.RunSQL SQL
DoCmd.SetWarnings True
End Sub

Need top3 records in MS Access

I have to create a text box in MS Access where users are able to see the top 3 records of a particular result set. So even if the query results in 5 records I only want it to display the top 3 records as three textboxes (sometimes the result may also be 1,2 or 0 records).
I took the easy way out and created a new subform which was connected to the parent form using master/child field. The textbox was placed in the details part of the subform and as a recordsource of the subfrom used the following query:
Select top 3 tbl1.column1, tbl1.column2
from tbl1
column1 is the control source for the textbox and column2 is the column I have used for master/child link.
Now the catch is that the query works fine when I use it without top 3. But when I use top 3 the textbox suddenly disappears and the subform is completely blank.
I am not able to identify the cause of the error. My guess is that it has something to do with type of the subform. Not sure.
Is there any other way I can have a text box whose number can vary on the basis of the results?(but limiting the resultset to 3)
Appreciate the help.
Textbox are not meant to hold more than 1 value.
You are trying to assign three results of 2 columns to one textbox(No can do).
Use listbox to populate as you are doing, assigning the query you just wrote in the rowsource of the list(no subforms needed). This way users will see the three records.
You could use a textbox in order to accomplish what you are trying to do. But will require some VBA coding to accomplish this.
Public function CombineValuesForTextBox() as string
Dim rst as dao.recordset
Dim strSQL as string
strSQL = "SELECT TOP 3 tbl1.Column1 as field1, tbl1.Column2 as field2 " & _
"FROM tbl1;"
set rst = currentdb.openrecordset(strsql)
if rst.recordcount = 0 then 'Checks if the recordset has records or not
CombineValuesForTextBox = "No records found"
goto EndCode 'Or replace with what actions to take if no records are found
else
rst.movelast 'Forces the recordset to fully load
rst.movefirst
do while not rst.eof
if CombineValuesForTextBox = "" or CombineValuesForTextBox = empty then
CombineValuesForTextBox = rst![field1] & " - " & rst![Field2]
else
CombineValuesForTextBox = CombineValuesForTextBox & vbcrlf & _
rst![field1] & " - " & rst![Field2]
end if
Loop
end if
rst.close
set rst = nothing
EndCode:
if not rst is nothing then
rst.close
set rst = nothing
end if
end function
Then on your form put in the code (be sure the textbox is unbound...)
me.textbox = CombineValuesForTextBox

MS Access multi field search with empty fields or multiple selections from list boxes

can some one kindly help me with MS Access? My problem is similar to the one in the following link:
MS Access multi field search with empty fields
but in my case, each search field is a list box from which we can select multiple things.
In my case, the user of the database application will enter start date and end date (text boxes) which will populate the list boxes (cost center, item number, employee id) from a single database table matching the rows that have effective date falling between start date and end date. After populating the list boxes, the user has the choice to either select multiple cost centers or leave the search field blank, multiple item numbers or blank, multiple employee numbers or blank. After selecting, if the command button display results is pressed, we should be able to get the results which satisfy all these search criteria. For example, if I select cost centers 1301, 1302 and employee no.s 492128, 492690, 492959 and leave the item numbers search field blank, then in the data table, all the entries that match these cost centers and employee no.s (all the search fields are separate columns) which fall between the start date and end date should be displayed.
I am unable to get the logic in VB. Please guide me through.
You'll need to build up an sql statement in vba then run it using a recordset, to get the results back.
Obviously I dont know what the data you'll need to get is, or from the tables you;ll get it from, however the where clause needs to be built as follows:
dim wc as string
wc = wc & iif(lst_costcenter.ItemsSelected.Count = 0, "", " AND " & InClause(lst_costcenter, "tablename.columnname", false))
wc = wc & iif(lst_itemnumber.ItemsSelected.Count = 0, "", " AND " & InClause( ...
Finally when building the sql statement, you'll need to chop of the first "AND" in wc & replace it with "WHERE"
wc = iif(wc <> "", " WHERE " & mid(trim(wc), 5), "")
InClause is a function that you need to add in a module, or in the enquiry form itself:
It uses 3 arguments:
1. The listbox control to build an in clause for,
2. A string comprising tablename-dot-columnname being the table/column to be filtered for the values selected in the listbox, &
3. True/False according to whether the datatype of the column is string (true) or numeric (false)
Public Function InClause(lst as ListBox, tblcol as string, isAlpha as boolean)
Dim si As String
Dim vv As Variant
For Each vv In lstBox.ItemsSelected
If isAlpha Then
si = si & "," & Chr(34) & lstBox.Column(0, vv) & Chr(34)
Else
si = si & "," & lstBox.Column(0, vv)
End If
Next vv
If si <> "" Then
si = "(" & tblcol & " IN (" & mid(si, 2) & "))"
End If
InClause = si
End Function
Hope this helps