I can't work out where I am going wrong with my code. When the user selects a value in the combo box, i want it to go to the Consultants table and grab the default rate for that consultant and stick it in the Hourly Rate text box. This is the msg that I get when I update the combobox.
Private Sub cmbConsultant_Change()
Dim db As Database
Dim rs As DAO.Recordset ''Requires reference to Microsoft DAO x.x Library
Dim strSQL As String
strSQL = "defaultFee * FROM tblConsultants WHERE ID = """ & Me!cmbConsultant & """"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
If rs.RecordCount > 0 Then
Me.txtHourlyRate = rs!CountOfEndDeviceType
Else
Me.txtHourlyRate = ""
End If
Set rs = Nothing
Set db = Nothing
End Sub
You could use DLookup for this - much simpler:
Private Sub cmbConsultant_Change()
Me!txtHourlyRate.Value = DLookup("defaultFee", "tblConsultants", "ID = '" & Me!cmbConsultant.Value & "'")
End Sub
However, most likely your ID is numeric, thus:
Private Sub cmbConsultant_Change()
Me!txtHourlyRate.Value = DLookup("defaultFee", "tblConsultants", "ID = " & Me!cmbConsultant.Value & "")
End Sub
I Think You need some SELECT Here
strSQL = "defaultFee * FROM tblConsultants WHERE ID = """ & Me!cmbConsultant & """"
It Should Be:
strSQL = "SELECT defaultFee AS [CountOfEndDeviceType] FROM tblConsultants WHERE ID = """ & Me!cmbConsultant & """"
Also Note, That [CountOfEndDeviceType] Must be a FieldName, SO I've put it in a Select statement.
Related
I am trying to open form X through form Y, where docid = docid
form X's table has a primary key column named "abcid" (the matching id)
I am trying to pass the label name of form Y's textbox's label "abcid" as string "abcid", the idea is to pass the column name dynamically whatever the used form is ==> in VBA OpenForm WHERE condition, but it doesn't execute properly or opens a blank form. code below:
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim checklistformName As String
Dim viewdocformName As String
Dim currentformName As String
currentformName = Screen.ActiveForm.Name
'Debug.Print currentformName
Dim docidcolumnName As String
docidcolumnName = Forms(currentformName).Controls(docid).Caption
Debug.Print docidcolumnName
Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT checklistformname FROM CyclesDefinitions WHERE cycledefid = " & Forms(currentformName)![cycledefid])
Do Until rs1.EOF = True
checklistformName = rs1(0)
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
Set rs2 = CurrentDb.OpenRecordset("SELECT DISTINCT viewdocformname FROM CyclesDefinitions WHERE cycledefid = " & Forms(currentformName)![cycledefid])
Do Until rs2.EOF = True
viewdocformName = rs2(0)
rs2.MoveNext
Loop
rs2.Close
Set rs2 = Nothing
Debug.Print currentformName & " - " & checklistformName & " - " & viewdocformName
DoCmd.OpenForm viewdocformName, , , " & docidcolumnname & " = " & Forms(checklistformName)![docid], acFormReadOnly
alright, I solved the OpenForm with string dilemma with the following solution after testing a statically predefined string:
DoCmd.OpenForm viewdocformName, , , "" & docidcolumnName & " = " & Forms(checklistformName)![docid], acFormReadOnly
it just needed the proper concatenation, and instead of messing with the forms!frmname syntax, because I can't find the proper return value, I set the label name on form to pkcolname and recalled it in VBA like this:
docidcolumnName = Me.pkcolname.Caption:
now everything is working as expected and required.
I have the following VBA code which populates a treeview control with the parent table Groups and then the child table Categories, I also have a child to categories named Section. I would like to be able to add a third level to my treeview control, so I can display section. However, I don't know how to do this correctly. Any help on this subject would be greatly appreciated.
I am trying to use the same method of adding a child level as I have done with the group and categories; but unsuccessfully so far.
I am not sure if my original code is entirely correct, but it appears to work ok.
I am using Microsoft treeview control version 6.0, if that makes any difference.
Private Sub Form_Load()
Dim nodX As Node
Dim MyDB As DAO.Database
Dim MyRS As DAO.Recordset
Dim MyRSChild As DAO.Recordset
Dim strSQL As String
Set MyDB = CurrentDb()
Set MyRS = MyDB.OpenRecordset("SELECT * FROM Prt_Group ORDER BY Group_Number", dbOpenDynaset)
Set nodX = Treeview1.Nodes.Add(, , , "Parts List Treeview")
'Populate grp Nodes
Do While Not MyRS.EOF
Set nodX = Treeview1.Nodes.Add(1, tvwChild, "Group" & MyRS![PartGroupID], MyRS![Group_Number] & " - " & MyRS![Group_Description])
nodX.EnsureVisible
MyRS.MoveNext
Loop
strSQL = "Select * From Prt_Category ORDER BY PartCat_Number"
Set MyRSChild = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
'Populate category Nodes
Do While Not MyRSChild.EOF
Set nodX = Treeview1.Nodes.Add("Group" & MyRSChild![PartGroupID], tvwChild, "A" & CStr(MyRSChild![PartCatID]), _
" " & MyRSChild![PartCat_Number] & " - " & _
MyRSChild![PartCat_Description])
MyRSChild.MoveNext
Loop
MyRSChild.Close
MyRS.Close
Set MyRSChild = Nothing
Set MyRS = Nothing
End Sub
Having not enough information to provide a full answer I just can help you a little with this:
Private Sub Form_Load()
'.....
'Populate category Nodes
Do While Not MyRSChild.EOF
Set nodX = Treeview1.Nodes.Add("Group" & MyRSChild![PartGroupID], tvwChild, "A" & CStr(MyRSChild![PartCatID]), _
" " & MyRSChild![PartCat_Number] & " - " & _
MyRSChild![PartCat_Description])
'insert third level node begins here
'Maybe do a dataset operation on "Section table" and a while loop
Treeview1.Nodes.Add nodx, tvwChild, "KEYOFSECTION", "LABELOFSECTION"
MyRSChild.MoveNext
Loop
'...
End Sub
Change "KEYOFSECTION" with a unique key and "LABELOFSECTION" with an appropriate Section label
I have used the following code that successfully works. I'm not sure if it is the most efficient way of coding this, but it does work. This page helped me understand the node object.
Private Sub Form_Load()
Dim nodX As Node
Dim MyDB As DAO.Database
Dim MyRS As DAO.Recordset
Dim MyRSChild As DAO.Recordset
Dim strSQL As String
Set MyDB = CurrentDb()
Set MyRS = MyDB.OpenRecordset("SELECT * FROM Prt_Group ORDER BY Group_Number asc", dbOpenDynaset)
Set nodX = Treeview1.Nodes.Add(, , , "Groups/Categories/Sections Treeview")
'Populate grp Nodes
Do While Not MyRS.EOF
Set nodX = Treeview1.Nodes.Add(1, tvwChild, "Group" & MyRS![PartGroupID], MyRS![Group_Number] & " - " & MyRS![Group_Description])
nodX.EnsureVisible
MyRS.MoveNext
Loop
strSQL = "Select * From Prt_Category ORDER BY PartCat_Number ASC"
Set MyRSChild = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
'Populate category Nodes
Do While Not MyRSChild.EOF
Set nodX = Treeview1.Nodes.Add("Group" & MyRSChild![PartGroupID], tvwChild, "A" & CStr(MyRSChild![PartCatID]), _
" " & MyRSChild![PartCat_Number] & " - " & _
MyRSChild![PartCat_Description])
MyRSChild.MoveNext
Loop
'-------------------NEW CODE FOR THIRD LEVEL----------------------------
Dim strSQL1 As String
Dim myRSChild1 As DAO.Recordset
strSQL1 = "Select * From Prt_Section ORDER BY Section_Number"
Set myRSChild1 = MyDB.OpenRecordset(strSQL1, dbOpenSnapshot)
Do While Not myRSChild1.EOF
Set nodX = Treeview1.Nodes.Add("A" & CStr(myRSChild1![PartCatID]), tvwChild, "B" & CStr(myRSChild1![SectionID]), _
" " & myRSChild1![Section_Number] & " - " & _
myRSChild1![Section_Description])
myRSChild1.MoveNext
Loop
'------------- END OF ADDITIONAL CODE-----------------------
'Root Text Bold
Treeview1.Nodes(1).Bold = True
MyRSChild.Close
MyRS.Close
myRSChild1.Close
Set MyRSChild = Nothing
Set MyRS = Nothing
Set myRSChild1 = Nothing
end sub
I have two tables and I have a form linking to one of them. I want to check a value and if it is true, add the record the other table by using VBA.
Can anyone help me, please?
This is my code, but it does not work:
Dim rec1 As DAO.Recordset
Dim rec2 As DAO.Recordset
Set rec1 = CurrentDb.OpenRecordset("TotalTPAq")
Set rec2 = CurrentDb.OpenRecordset("Visi")
rec1.MoveFirst
Do Until rec1.EOF
If rec1!Date = PlanDate.Value Then ' planDate is a text box
rec2.AddNew
rec2![Planing Date History] = PlanDate.Value
rec2.Update
rec2.Close
End If
rec1.MoveNext
Loop
rec1.Close
Set rec2 = Nothing
Set rec1 = Nothing
DoCmd.Close
This should provide a start for you:
'Run query to fill table
Private Sub btnRnQry_Click()
'No value entered
If IsNull(Me.txtEntry) Or Me.txtEntry = "" Then
MsgBox ("Is null or empty")
Else
'Assign value to variable
Dim entry As String
entry = Me.txtEntry
Dim sql As String
sql = "INSERT INTO tableTwo ([First Name],Surname,[Phone Number] )" & _
"SELECT * " & _
"FROM tableOne " & _
"WHERE [First Name] = '" & entry & "';"
'Run the SQL
DoCmd.RunSQL sql
End If
End Sub
I have the following code:
Public Function BuildSQL(stQueryName As String, stWhereClause As String) As String
On Error GoTo Err_BuildSQL
Dim SQLcmd As String
Dim intPos As Integer
Dim db As Database
Dim qryOrig As QueryDef
Set db = CurrentDb()
Set qryOrig = db.QueryDefs(stQueryName)
SQLcmd = qryOrig.SQL
intPos = InStr(SQLcmd, "WHERE")
If intPos > 0 Then
SQLcmd = Left(SQLcmd, intPos - 1)
End If
intPos = InStr(SQLcmd, ";")
If intPos > 0 Then
SQLcmd = Left(SQLcmd, intPos - 1)
End If
If Not (stWhereClause = "") Then
SQLcmd = Trim(SQLcmd) & " WHERE " & stWhereClause & ";"
Else
SQLcmd = Trim(SQLcmd) & ";"
End If
BuildSQL = SQLcmd
Exit_BuildSQL:
Set qryOrig = Nothing
Set db = Nothing
Exit Function
Err_BuildSQL:
MsgBox Err.Description
Resume Exit_BuildSQL
End Function
Private Sub SandBox_Click()
On Error GoTo Err_SandBox_Click
Dim db As Database
Dim rs As Recordset
Dim stSQL As String
Dim stFrmName As String
Dim stQryName As String
Dim stSQLWhere As String
Dim stIDList As String
stFrmName = "Libri"
stQryName = "Libri_All_Query"
'Define WHERE clause
stSQLWhere = ""
If Not (IsNull([Forms]![Libreria]![Editore]) Or [Forms]![Libreria]![Editore] = "") Then
stSQLWhere = stSQLWhere & "Libri_Editori.Editore = '" & [Forms]![Libreria]![Editore] & "'"
End If
If Not (IsNull([Forms]![Libreria]![CognomeAutore]) Or [Forms]![Libreria]![CognomeAutore] = "") Then
If (stSQLWhere = "") Then
stSQLWhere = stSQLWhere & "Autori.Cognome = '" & [Forms]![Libreria]![CognomeAutore] & "'"
Else
stSQLWhere = stSQLWhere & " AND Autori.Cognome = '" & [Forms]![Libreria]![CognomeAutore] & "'"
End If
End If
'Here several more fields of the search form will be checked and added
stSQL = BuildSQL(stQryName, stSQLWhere)
'*** Code in question!
Set db = CurrentDb()
Set rs = db.OpenRecordset(stSQL)
If Not (rs.EOF And rs.BOF) Then
stIDList = "("
rs.MoveFirst
Do Until rs.EOF = True
If (stIDList = "(") Then
stIDList = stIDList & rs.Fields(0)
Else
stIDList = stIDList & ", " & rs.Fields(0)
End If
rs.MoveNext
Loop
stIDList = stIDList & ")"
Else
Err.Description = "Errore! Recordset vuoto."
Resume Err_SandBox_Click
End If
DoCmd.OpenForm stFrmName, , , , acFormReadOnly
Access.Forms(stFrmName).RecordSource = "SELECT * FROM Libri WHERE Libri.ID IN " & stIDList
'**** End code in question
Exit_SandBox_Click:
Set db = Nothing
Set rs = Nothing
Exit Sub
Err_SandBox_Click:
MsgBox Err.Description
Resume Exit_SandBox_Click
End Sub
This code works as I want but "looks" slow even with a test DB with only a few records in each table.
I believe the time is spent (how can I check if this is true?) in the loop between comments.
Is there a more basic, obvious and efficient way to filter the form than creating a recordset and looping through it as I am doing?
The form "Libri" is a big one with several subform to be able to see all the data of a Book.
The query "Libri_All_Query" is a join of almost all tables in the DB and the code shown is executed from a form where I plan to add all possible search fields.
Forms have a filter property:
stWhereClause = "Title Like '" & Me.txtSearch & "*'"
Me.Filter = stWhereClause
Me.FilterOn = True
The filter should be constructed in a similar way to a WHERE statement. There are some limitations compared with Where. You may wish to check with DCount that records will be returned.
EDIT
If you want a set of records where a subform contains only certain records, you need something on these lines:
SELECT b.Title
FROM Books b
WHERE b.ID IN (
SELECT j.BookID FROM BooksAuthorJunction j
INNER JOIN Authors a ON j.AuthorID = a.ID
WHERE a.Author Like "Arn*")
There are advantages in building more that one form, books as a main form and authors as a subform, then authors as a main form and books as a subform. It is often easier on the user.
Database Structure:
UserName String
Location String
Price Number
Requirement:
I have listbox with some items into it say 100. The user will select only 10 randomly in the listbox (after changing the MULTISELECT to 2fmMultiselect property). I will have search button. Once I select and click Search, the total price of selected items has to be calculated and displayed.
My search code ( Thanks to Alex sir)
enter code here
Private Sub CommandButton4_Click()
Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set rs = New ADODB.Recordset
sName = Replace$(TextBox1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
If (rs.EOF) Then
MsgBox "no match"
Else
TextBox3.Text = rs("UserName") & " " & rs("Location")
rs.Close
End If
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
That code was just to search and display in a textbox.
Now, I need to total the price of what all UserName field selected by the user from listbox.
Try this, but make sure the bound column in your list box is the ID field of your table.
Private Function SelectedListString(lstSelected As Access.ListBox) As String
'Loop though a list and get the IDs of all the selected items
'Assumes the bound column is the contains the ID field
Dim sList As String
Dim vSelected As Variant
With lstSelected
For Each vSelected In .ItemsSelected
sList = sList & .ItemData(vSelected) & ","
Next
End With
If sList <> "" Then sList = Left(sList, Len(sList) - 1) 'trim trailing coma
SelectedListString = sList
End Function
you can use the result in an IN statement in your SQL
Dim sSql As String
If myListbox.ItemsSelected.Count > 0 Then
sSql = "SELECT * FROM table WHERE IDField IN (" & SelectedListString(myListbox) & ")"
End If