Microsoft Access 2010 interdependencies in Forms (fill out one cell, automatically fill another) - ms-access

In excel, I know this is the VLOOKUP function, however, being a beginner at Access, I have no clue how to do this.
I have halls (from A to H), who all have their own teamleader (eg A-->Ben, B-->Michael, C-->Dave, etc). I would like to select just the hall, and the teamleader will automatically show up in the next field on the form. At the end, all will be registered in a table.
I have currently build this equation to fill out a specific value in a cell (dependent on the value of another cell), but it is giving an error message. What am I doing wrong?
Option Compare Database
Dim db As DAO.Database
Dim rst As DAO.Recordset
Private Sub Hal_AfterUpdate()
Set db = CurrentDb
'SELECT Voormannen.Voorman, Voormannen.Hal
'FROM Voormannen
'WHERE (((Voormannen.Hal)=[Formulieren]![DSM formulier]![Hal]));
strSQL = "SELECT Voormannen.Voorman, Voormannen.Hal FROM Voormannen WHERE [Voormannen]![Hal]=[Forms]![DSM formulier]![Hal]"
Set rst = db.OpenRecordset(strSQL)
rst.MoveFirst
Me.Tekst304 = rst![Voorman]
rst.Close
Set rst = Nothing
Me.Refresh
End Sub

Assuming your SQL string returns a correct dataset, try replacing this:
Me.Tekst304 = rst![Voorman]
with this:
Me.Tekst304.Text = rst("Voorman")
If your SQL string does not return a correct dataset, try changing it to this:
strSQL = "SELECT Voorman, Hal FROM Voormannen " & _
"WHERE Hal = '" & Forms![DSM formulier]!Hal.Text & "'"
You need to surround your control reference with ampersands (&) otherwise VBA doesn't know you're referencing a control.

Related

Using SQL and VBA in combination

Okay I'm new here and will be my first question, I'm getting stuck with my code that I'm busy with.
I keep bumping same error which is related to the Runtime error: 3129 in Access Visual Basic
Now it is an importing button function set in a Public Sub check below my code:
Public Sub ImportDataTablebtn_Click()
Dim strSQL As String
Dim db As DAO.Database
Dim tbl1 As DAO.TableDef
Dim tbl2 As DAO.TableDef
Dim fld1tbl1 As DAO.Field
Dim fld2tbl1 As DAO.Field
Dim fld3tbl1 As DAO.Field
Dim fld1tbl2 As DAO.Field
Dim fld2tbl2 As DAO.Field
Dim fld3tbl2 As DAO.Field
Set db = CurrentDb
Set tbl1 = db.TableDefs("Clicks Returns")
Set tbl2 = db.TableDefs("Oct 2015 Clicks Returns")
Set fld1tbl1 = tbl1.Fields("SKU")
Set fld2tbl1 = tbl1.Fields("Item Description")
Set fld3tbl1 = tbl1.Fields("Oct 2015 FIN YTD TY % Returns")
Set fld1tbl2 = tbl2.Fields("Sku")
Set fld2tbl2 = tbl2.Fields("Item Description")
Set fld3tbl2 = tbl2.Fields("F21")
DoCmd.RunSQL strSQL
strSQL = "INSERT INTO tbl1 (fld1tbl1, fld2tbl1, fld3tbl1)" & _
"SELECT fld1tbl2, fld2tbl2 fld3tbl2 FROM tbl2;"
Set db = Nothing
End Sub
Now I know some of my lines like the table rename and field might not really be required, though I thought that it would just make it easier with the code...
Please let me know where I'm making my error as I feel like going crazy by keep looking at it over and over.
In the database is the tables that I'm referring towards and I want to move the certain fields from the one table to the other table as it is imported excel sheets, I'm busy making it an automated system where someone would just click on buttons on a form and it will sort out the data.
Thank you for taking the time to read this essay and also answering it
There are a couple of mistakes in your code.
First the code will not substitute your variables for the table/field names. So the string SELECT fld1tbl2 is not converted to SELECT [Item Description].
Second you are trying to run your query before you have built it.
Finally Access uses VBA and not VBScript. It's a different language. While they have much in common there are some important differences. Stick to the the VBA tag and you will be more likely to get the answers you need.
I've refactored your code. This version builds and then runs the query.
Public Sub ImportDataTablebtn_Click()
Dim strSQL As String
' Build Query.
strSQL = "INSERT INTO [Clicks Returns] " & _
"(SKU, [Item Description], [Oct 2015 FIN YTD TY % Returns]) " & _
"SELECT Sku, [Item Description], F21 FROM [Oct 2015 Clicks Returns];"
' Run Query.
DoCmd.RunSQL strSQL
End Sub

Get Record based on form textbox value

I am trying to get a record based on the value contain within the textbox on a form. i.e i type in the information into the textbox and other values associated with that value are returned to other textbox on the form.
I thought this would be easy but can't seem to get it to work.
Currently I was trying
Dim rst As DAO.Recordset
Dim SQL As String
Dim SQL2 As String
SQL = "SELECT tblmytbl.[IDCODE]"
"FROM tblmytbl " & _
"WHERE (((tblmytbl.[IDCODE]) = forms!myform!mybox.value "
Set db = CurrentDb
Set rst = db.OpenRecordset(SQL)
If Not ((rst.BOF = True) And (rst.EOF = True)) Then
Forms!myform!Text102 = rst.Fields("[Name]")
Forms!myform!Text103 = rst.Fields("[Surname]")enter code here
Note: The search information is alphanumeric and i have tried without the .value
Any help would be appreciated.
Thanks
The SQL you send to the server can't access the form. However, you can concatenate the value into the string that you send like:
" WHERE (((mytable.myfield) = '" & FixQuotes(Forms!myform!mybox.value) & "') " & _
Note, you may need to defend yourself against SQL injection, a simple (but not complete) defense would be something like:
Public Function FixQuotes(input as string) As String
FixQuotes = Replace(input,"'","''")
End Function
EDIT:
Based on your updated code, there's quite a number of changes you need to make. Beyond my statement above, the .OpenRecordset only applies to full tables, you can't use it with a SELECT statement. Instead, you have to instantiate a QueryDef. On top of that, you try to reference fields you didn't include in the query. Also, you can simplify the expression Forms!myform! to Me (which could help if you want to reuse the code somewhere else) So your code should look something like this:
Dim db as Database 'always dim everything, you should use Option Explicit'
Dim rst as Recordset 'DAO is the default anyway'
Dim qdf as QueryDef 'this object is required for queries'
Set db = CurrentDb
'prepare single-use query, to return the values you're going to use
'as mentioned before, the query doesn't have access to the form
'we can use Me since it references the form'
' use TOP 1 since you only expect 1 record'
Set qdf = db.CreateQueryDef("","SELECT TOP 1 Name,Surname FROM tblmytbl " & _
"WHERE IDCODE = '" & FixQuotes(Me.mybox.value) & "';")
Set rst = qdf.OpenRecordset(DbOpenForwardOnly)
'forwardonly since you only care about the first record'
If Not rst.EOF Then 'ForwardOnly has to start at the first record'
Me.Text102.Value = rst!Name
Me.Text103.Value = rst!Surname
'I highly suggest giving these boxes better names'
Else
'no record found'
End if
rst.Close
qdf.Close
db.Close 'close these objects, it can sometimes cause memory leaks otherwise'

Run Time Error 3464: Data Type Mismatch in criteria expression

I have a form in Access 2010 with Two text boxes(AIPIDTxt to enter the search criteria and AIPResultTxt to display results) and a Button(Search button). I also have a Table Table1 in Access. When I click the Search Button, I need to execute a query whose criteria is in AIPIDTxt Textbox in the form, store the result in a recordset and display the results in the textbox AIPResultTxt. So I typed in the following VBA Code in the Button Event handler.
Private Sub SearchB_Click()
Dim localConnection As ADODB.Connection
Dim query As String
Dim aipid_rs As ADODB.Recordset
Dim db As Database
Set db = CurrentDb
Set localConnection = CurrentProject.AccessConnection
MsgBox "Local Connection successful"
query = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]=
" & [Forms]![AIPIDSearchF]![AIPIDTxt] & ""
Set aipid_rs = db.OpenRecordset(query)
Me.AIPResultTxt.Text = aipid_rs![AIP Name]
End Sub
But when I click the button I get Local Connection Successful Message Box and then a Run Time Error 3464 in the line:
Set aipid_rs= db.OpenRecordset(query)
I have searched for similar errors and made corrections. But the error keeps coming. Is there something wrong with my query? Couldn't figure out the error. The table is a local table. So I can directly give [Table1] and field names in the query in vba. Tried adding delimiters because the fields are text fields. But that didn't work as well. I could not give the following query as well:
query = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]= " & [Forms]![AIPIDSearchF]!
[AIPIDTxt].Text & ""
This gave me a run time error stating text cannot be referenced from controls that have lost focus. My criteria is text in the text box. The text box loses focus when i click the button. But when I googled for the error, solutions were to remove ".Text". So, I ended up with the above query. Do not know what is wrong with the line:
Set aipid_rs= db.OpenRecordset(query)
I suspect you have more than one problem with that code. But Access complains about only the first problem it finds. Look again at these 2 lines ...
Dim aipid_rs As ADODB.Recordset
Set aipid_rs = db.OpenRecordset(query)
OpenRecordset is a DAO method which returns a DAO recordset. But the code attempts to assign it to aipid_rs which was declared As ADODB.Recordset. Those recordset types are not compatible.
There is an ADO connection object variable, localConnection, which is not used for anything later. Although it doesn't trigger an error, it's just not useful. And actually I don't see any reason to use anything from ADO for this task.
I suggest you try this version of your code ...
'Dim localConnection As ADODB.Connection
'Dim query As String ' query is a reserved word
Dim strQuery As String
'Dim aipid_rs As ADODB.Recordset
Dim aipid_rs As DAO.Recordset
Dim db As Database
Set db = CurrentDb
'Set localConnection = CurrentProject.AccessConnection
'MsgBox "Local Connection successful"
' you said [AIP ID] is text type, so include quotes around
' the text box value
strQuery = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]= '" & _
[Forms]![AIPIDSearchF]![AIPIDTxt] & "'"
Debug.Print strQuery
DoCmd.RunCommand acCmdDebugWindow
Set aipid_rs = db.OpenRecordset(strQuery)
'Me.AIPResultTxt.Text = aipid_rs![AIP Name] ' .Text property is only
' available when control has focus; it will trigger
' an error at any other time
Me.AIPResultTxt.Value = aipid_rs![AIP Name]
Note Debug.Print strQuery will display the text of the SELECT statement in the Immediate window, and DoCmd.RunCommand acCmdDebugWindow opens the Immediate window. If you still have a problem with the query, copy the statement text and paste it into SQL View of a new query for testing.
Finally I'm curious whether this might give you what you need with much less code ...
Private Sub SearchB_Click()
Me.AIPResultTxt.Value = DLookup("[AIP Name]", "Table1", _
"[AIP ID]='" & Me.AIPIDTxt & "'")
End Sub
You are using an ADO recordset, therefore your open syntax is incorrect. The following should work for you (except you may get an error setting the text if the control doesn't have focus...)
Dim localConnection As ADODB.Connection
Dim query As String
Dim aipid_rs As ADODB.Recordset
Dim db As Database
Set db = CurrentDb
Set localConnection = CurrentProject.AccessConnection
MsgBox "Local Connection successful"
query = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]= '" & [Forms]![AIPIDSearchF]![AIPIDTxt] & "'"
'Set aipid_rs = db.OpenRecordset(query)
Set aipid_rs = New ADODB.Recordset
aipid_rs.Open query, localConnection, adOpenStatic, adLockReadOnly
If Not aipid_rs.EOF Then
Me.AIPResultTxt.Text = aipid_rs![AIP Name]
Else
MsgBox "No records!!"
End If
aipid_rs.Close
Set aipid_rs = Nothing
localConnection.Close
Set localConnection = Nothing
db.Close
Set db = Nothing
OK, So I have been searching for a simple search element for quite awhile...
I have tried using subforms and I have tried recordsets. All of these have given me the information. But not the compactness I was looking for, thanks!!!
using the DOA stuf is great but not for my application.
using the above:
Me.AIPResultTxt.Value = DLookup("[AIP Name]", "Table1", _
"[AIP ID]='" & Me.AIPIDTxt & "'")
I have the compactness of code I was looking for...
THanks!!!
T

Advanced Filter Criteria in Access

The issue is simple but I just cant figure it out.
I have two tables in access, one with records and another with "key words". I need to filter the records containing certain "key words". In other words, use one table field as a filter criteria for the other, but without linking them because the "key words" table just contains random words instead of a whole record.
In excel I can run an advanced filter on my records and just specify as criteria the list of key words (and using wildcards), but in acces I havent found a way to filter according to another table fields.
Any ideas about it?
You may need to create a function that spits out custom SQL with all the keywords in it. Here is an example to get you started.
Public Function fGetTrashRecords()
'add your own error handling
Dim SQL As String
Dim rst As DAO.Recordset
Dim rstTrash As DAO.Recordset
Dim db As DAO.Database
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT sKeyWord FROM tblBadKeyWords", dbOpenSnapshot)
If Not rst Is Nothing Then
rst.MoveFirst
Do While Not rst.EOF
SQL = SQL & " strFieldContaingKeyWord LIKE *'" & rst!sKeyWord & "'* OR"
rst.MoveNext
Loop
If SQL > "" Then SQL = Left(SQL, Len(SQL) - 2) 'get rid of the last OR
rst.Close
Set rst = Nothing
End If
If SQL > "" Then
Set rstTrash = db.OpenRecordset("SELECT * FROM tblHasKeyWords WHERE " & SQL, dbOpenDynaset, dbSeeChanges)
If Not rstTrash Is Nothing Then
rstTrash.MoveFirst
Do While Not rstTrash.EOF
Debug.Print rstTrash!ID
rstTrash.MoveNext
Loop
rstTrash.Close
Set rstTrash = Nothing
End If
End If
Set db = Nothing
End Function

How to insert several fields into a table using ADO when two of the fields contain commas

I have an ado created recordset in access 2010 it returns 9 different fields from a stored procedure on sql server 2008 r2.
I am trying to use this recordset (which does populate) to insert all of the records into a table that matches the output. My issue is that two of the fields are name fields that have commas in them. For example Smith, Joseph-- I need to insert that comma into the appropriate field. Right now it throws an error because of the comma in the field.
Here is the code that I am using:
Option Compare Database
'Executes the filtering routine
Private Sub cmdApplyFilter_Click()
'If txtStartDate.Value And txtEndDate.Value Is Not Null Then
' QuickFilter
'Else
' DefaultRun
'End If
QuickFilter
'********** Filter as you type **********
'Private Sub txtFilter_Change()
' QuickFilter
'End Sub
End Sub
'Perform the actual filtering on the subform
Private Sub QuickFilter()
Dim Sql As String
Dim filter As String
If txtStartDate = vbNullString Then
'Reset the filter if the textbox is empty
'This will be the default sql statement to fill the subreport
SubForm.Form.FilterOn = False
Else
'Some common substitutions that users may have already inserted as wildchars
filter = Replace(txtStartDate, "%", "*")
filter = Replace("*" & filter & "*", "**", "*")
'Construct the filter for the sql statement
'/*********** GROUP BY GOES HERE ***********/
'Assign the filter to the subform
'SubForm.Form.filter = Sql
'SubFomr.Form.FilterOn = True
End If
End Sub
Private Sub Form_Load()
'Sets up the connection with the sql server database retrieves the stored procedure, executes it and puts the result set into a table
Dim Conn As ADODB.Connection
Dim Cmd As ADODB.Command
Dim Rs As ADODB.Recordset
Dim rs1 As ADODB.Recordset
Dim Connect As String
Dim filter As String
Connect = "Provider =SQLNCLI10; Data Source=10.50.50.140; Initial Catalog=CCVG; User Id = oe; Password = Orth03c0; "
'Establish the connection with sql server
Set Conn = New ADODB.Connection
Conn.ConnectionString = Connect
Conn.Open
'Open the recorset
Set Cmd = New ADODB.Command
Cmd.ActiveConnection = Conn
Cmd.CommandText = "dbo.cusGenNoNotesReport"
Cmd.CommandType = adCmdStoredProc
Set Rs = Cmd.Execute()
Dim x As Integer
If Not Rs.BOF And Not Rs.EOF Then
If Not Rs.BOF Then Rs.MoveFirst
Do Until Rs.EOF
For x = 0 To Rs.Fields.Count - 1
MsgBox Rs.Fields(x)
'DoCmd.RunSQL "INSERT INTO tblNoNotes (Provider, Facility, TicketNumber, Charges, FinancialClass, CPT, CPTDescription, PatientFullName, DateOfEntry) SELECT " & Rs.Fields(x).Value & ""
Next x
Rs.MoveNext
Loop
End If
'Process results from recordset, then close it.
'DoCmd.RunSQL "INSERT INTO tblNoNotes (Provider, Facility, TicketNumber, Charges, FinancialClass, CPT, CPTDescription, PatientFullName, DateOfEntry) VALUES (""" & Rs![Provider] & """,""" & Rs![Facility] & """ & Rs![TicketNumber] & """, """ & Rs![Charges] & """, """ & Rs![FinancialClass] & """, """ & Rs![CPT] & """, """ & Rs![CPTDescription] & """, """ & Rs![PatientFullName] & """, """ & Rs![DateOfEntry] & """ )"
Rs.Open
Rs.Close
Conn.Close
Set Rs = Nothing
Set Cmd = Nothing
Set Conn = Nothing
End Sub
You have an ADO Recordset, Rs, which contains data you want to add to your Access table. Instead of trying to fix the INSERT statement to add each row, it should be easier to open a DAO Recordset for the destination table and store the values from each ADO row by adding a new row the the DAO Recordset. Although this is still a RBAR (row by agonizing row) approach, it should be significantly faster than building and executing an INSERT statement for each row.
First of all, make sure to add Option Explicit to your module's Declarations section.
Option Compare Database
Option Explicit
Then use this code to append the ADO Recordset data to your table.
Dim db As DAO.Database
Dim rsDao As DAO.Recordset
Set db = CurrentDb
Set rsDao = db.OpenRecordset("tblNoNotes", _
dbOpenTable, dbAppendOnly + dbFailOnError)
Do While Not Rs.EOF
rsDao.AddNew
rsDao!Provider.Value = Rs!Provider.Value
rsDao!Facility.Value = Rs!Facility.Value
rsDao!TicketNumber.Value = Rs!TicketNumber.Value
rsDao!Charges.Value = Rs!Charges.Value
rsDao!FinancialClass.Value = Rs!FinancialClass.Value
rsDao!CPT.Value = Rs!CPT.Value
rsDao!CPTDescription.Value = Rs!CPTDescription.Value
rsDao!PatientFullName.Value = Rs!PatientFullName.Value
rsDao!DateOfEntry.Value = Rs!DateOfEntry.Value
rsDao.Update
Rs.MoveNext
Loop
rsDao.Close
Set rsDao = Nothing
Set db = Nothing
Note this approach means you needn't worry about whether PatientFullName contains a comma, or apostrophe ... or struggle with properly quoting field values to produce a valid INSERT statement. You simply store the value from one recordset field to the appropriate field in another recordset.
I think the real problem you're complaining about here is that your data in the ADO Recordset has quotes (sometimes called apostrophes) in it. Anytime quotes could possibly exist in your data you will need to check for and escape them before using the data in an SQL Statement. You will need to know this not only for inserts but also for performing filtering and creating WHERE statements as well. For example:
Replace(Rs![PatientFullName], "'", "''")
A simpler way to do this is to make your own little function. The "PQ" stands for pad quotes. You can name it whatever you want.
PQ(rs![PatientFullName])
Public Function PQ(s as String) as String
PQ = Replace(s, "'", "''")
End Function
But I also agree with HansUp that it's much easier to use recordsets for inserts. I basically never use SQL Insert statements anymore, except for places where I have no option such as SQL Server T-SQL.
Be aware that if you do want to use insert statements, you should consider using the following:
CurrentDb.Execute "INSERT INTO Statement Goes Here", dbFailOnError
This is considered to be a more robust solution than DoCmd.RunSQL, mostly because it runs in the context of the underlying Database Engine instead of the Access interface. Using CurrentDb.Execute prevents you from having to use DoCmd.SetWarning statements to turn off warnings.