I have problems with the wording of the criteria of a DCount function.
On click() I would like to have the number of occurrences of the field "YearMonth" in a tale in accordance with the value entered in an inbound fields called "Txt_entry".
My code ignores the criteria given (and returns 0) given that its wording is wrong but I cannot find out what would be the correct wording.
Private Sub Ctl3_Click()
Dim db As Database
Dim r As Recordset
Dim YearMonth As Field
Dim Txt_entry As String
Set db = CurrentDb()
Set r = db.OpenRecordset("Table")
Set YearMonth = r.Fields("YearMonth")
MsgBox (DCount("YearMonth", "Table", "[YearMonth]=" & Me.Txt_entry))
End Sub
Thanks!
You can always try:
For a string
DCount("YearMonth", "Table", "[YearMonth]= '" & Me.Txt_entry & "'")
For a date:
DCount("YearMonth", "Table", "[YearMonth]= #" & Me.Txt_entry & "#")
Depending how you store it in your database.
You dont need to set those variables for Dcount or Dlookup(assuming all you want is the count)
Variables only need to be set if you have some other criteria you want to enter in the Where clause of the dcount.
As for the me.Text_Entry , try me.Text_entry.value and see if the box has an actual value.
You can test it by throwing it into msgbox(me.txt_entry.value) That may be the cause of not getting a proper count. As the query would end up as
YearMonth = "" without a proper value.
Try this,
DCount("YearMonth", "Table", "[YearMonth]= #" & Format(Me.Txt_entry, "yyyy\/mm\/dd") & "#")
Related
I have a SQL statement that Selects any column where the word "No" shows up in a row. When I try to count the number of "No"'s I run in to a problem when there are multiple "No"'s in one row. It counts that as one instance (counting the row, not the "No").
SELECT tbl_CSRQA.ClaimantAdded, tbl_CSRQA.DocsPhoneCall, tbl_CSRQA.InsdDriverVehInfo, tbl_CSRQA.LossInfo, tbl_CSRQA.TemplateCalNotes, tbl_CSRQA.EmailtoLiab, tbl_CSRQA.ReserveScreen, tbl_CSRQA.InsNamePhone, tbl_CSRQA.Clerical, tbl_CSRQA.AdditionalSteps AS [Total Claim Errors Jan]
FROM tbl_CSRQA
WHERE tbl_CSRQA.CustomerServiceRep=[forms]![frm_CSRErrorTracking]![CSRNameCB] AND tbl_CSRQA.ClaimDate Between #1/1/2019# And #1/31/2019# AND
(tbl_CSRQA.ClaimantAdded="No" OR
tbl_CSRQA.DocsPhoneCall="No" OR
tbl_CSRQA.InsdDriverVehInfo="No" OR
tbl_CSRQA.LossInfo="No" OR
tbl_CSRQA.TemplateCalNotes="No" OR
tbl_CSRQA.EmailtoLiab="No" OR
tbl_CSRQA.ReserveScreen="No" OR
tbl_CSRQA.InsNamePhone="No" OR
tbl_CSRQA.Clerical="No" OR
tbl_CSRQA.AdditionalSteps="No");
Then in a report I am trying to use this;
=DCount("[Total Claim Errors Jan]","[qry_CSRAutoTotalClaimErrorsJan]")
The problem as I mentioned is that I want to count the number of "No"'s that appear, not the number of rows that have a "No" in it. How should I word this?
Add below function in a standard module, then in report =CountInstanceofNo()
Option Compare Text
Public Function CountInstanceofNo() As Long
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim fld As DAO.Field
Dim counter As Long
Set db = CurrentDb
Set rs = db.OpenRecordset("Select ClaimantAdded, DocsPhoneCall, InsdDriverVehInfo,LossInfo,TemplateCalNotes,EmailtoLiab, ReserveScreen, InsNamePhone, Clerical, AdditionalSteps from tbl_CSRQA Where CustomerServiceRep='" & [forms]![frm_CSRErrorTracking]![CSRNameCB] & "' AND ClaimDate Between #1/1/2019# And #1/31/2019#", dbOpenDynaset)
Do Until rs.EOF
For Each fld In rs.Fields
counter = counter + IIf(fld & "" = "No", 1, 0)
Next
rs.MoveNext
Loop
CountInstanceofNo = counter
rs.Close
Set rs = Nothing
Set db = Nothing
End Function
You can use Replace and an old trick to build an expression in your query:
NoCounts: (Len([Field1] & [Field2] & … & [FieldN]) - Len(Replace([Field1] & [Field2] & … & [FieldN]), "No", ""))) / Len("No")
If these were Yes/No type fields with values of -1/0, could construct a calculated field that adds all the other fields.
SELECT tbl_CSRQA.*,
10-Abs(ClaimantAdded + DocsPhoneCall + InsdDriverVehInfo + LossInfo + TemplateCalNotes +
EmailtoLiab + ReserveScreen + InsNamePhone + Clerical + AdditionalSteps) AS TotNo
FROM tbl_CSRQA
WHERE CustomerServiceRep=[forms]![frm_CSRErrorTracking]![CSRNameCB]
AND ClaimDate Between #1/1/2019# And #1/31/2019#;
Since these are apparently text fields, a single expression will probably be too long. Construct calculated fields with conditional expression for each field to convert to 1 or 0 then reference those calculated fields in the arithmetic expression. Alternatively, build a VBA custom function to return count of No's in each record.
Now Sum or DSum the TotNo calculated field.
I need help with a textbox field on an Access 2007 form. I'm trying to insert the result of a query into the text box control on the form. This is used soley as information for the user. The form supplies the query with parameters to get the value. The query works fine and returns the correct result. What I can't seem to figure out is how to pass the query result to the textbox. I’ve tried several different ways but with no luck.
(PS> I know a combo box can do a lookup, however I don’t want the user to have to click the dropdown just to select the value as there can only ever be one value result from the query.) I'm open to suggestions as I'm not a programmer or DB Admin, but I've taking a few classes on Access (enough to be dangerous).
Private Sub cbo3_Change()
Me.tbx2 = ("SELECT tbl_Billing.Savings_b FROM tbl_Billing GROUP BY tbl_Billing.UBI_b, tbl_Billing.TaxYr_b, tbl_Billing.TaxPrg_b, tbl_Billing.Savings_b HAVING (((tbl_Billing.UBI_b)=forms!f1_UpBilled!cbo1) And ((tbl_Billing.TaxYr_b)=forms!f1_Upbilled!cbo2) And ((tbl_Billing.TaxPrg_b)=forms!f1_UpBilled!cbo3));")
End Sub
If you wish to do this in run time, you need to do the following, I take the controls you are referring to in this is on the same form.
The very simple and straight forward way to get it done is as follows,
Private Sub cbo3_Change()
Dim tmpRS As DAO.Recordset
Set tmpRS = CurrentDb.OpenRecordset("SELECT tbl_Billing.Savings_b FROM tbl_Billing GROUP BY " & _
"tbl_Billing.UBI_b, tbl_Billing.TaxYr_b, tbl_Billing.TaxPrg_b, " & _
"tbl_Billing.Savings_b HAVING ((tbl_Billing.UBI_b = '" & Me.cbo1 & "') And (tbl_Billing.TaxYr_b = '" & Me.cbo2 & "') " & _
"And (tbl_Billing.TaxPrg_b = '" & Me.cbo3 & "'))")
If tmpRS.RecordCount > 0 Then
Me.tbx2 = tmpRS.Fields(0)
Else
Me.tbx2 = 0
End If
Set tmpRS = Nothing
End Sub
Just note, I have implied all your combo boxes are returning String and the field you are comparing against are Text type. If that is not the case, you need to make changes accordingly.
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'
I have a problem in Access 2010 VBA trying to read a record from table to write it into TextBoxes.
My table is "Products" and its ProductID field is numeric. I used this method before, but it just works for text fields, not for numeric fields (ProductID is autonumber).
Private Sub GetProduct(ID As TextBox, Name As TextBox, Price As TextBox)
If ID <> "" Then
Set db = CurrentDb
Set rs = db.OpenRecordset("Productos", dbOpenDynaset)
'PROBLEM IS HERE
rs.FindFirst "ProductID=" & "'" & ID & "'"
If rs.NoMatch Then
MsgBox "The producto doesn't exist."
Price = ""
Name = ""
Else
Name = rs!ProductName
Price = rs!Price
End If
rs.Close
Set rs = Nothing
Set db = Nothing
End If
End Sub
Please, help me. This is for a Final Proyect and I don't know other, but this method. Please help me.
Good to see you figured it out.
The problem is that ProductID is numeric and your code specifically tests for a text field
rs.FindFirst "ProductID=" & "'" & ID & "'"
putting a single quote each side of the parameter makes Access parse the parameter as a string.
If ID is 123, this will read
rs.FindFirst "ProductID='123'"
and you get a type error
I found a simple solution!
rs.FindFirst "ProductoID=" & ID
So the following VBA code I have will requery the form based on the Combo1 value equal to January. Eventually, I'll have X number of years in the Combo value and only want to display all records based on each year.
Is it possible to add additional VBA code to use the Criteria from the query instead of having X amount of queries and requery them based on the year.
Private Sub Combo1_AfterUpdate()
If Combo1.Value = "2013" Then
[Form_Main Form].RecordSource = "Main_Form_Query"
[Form_Main Form].Requery
End If
End Sub
You can construct the query in runtime (remember: a query object in access is just an sql statement)
So, let's asume that your data is stored in a table called tblMyData that has columns called month (String, month name) and year (Numeric, Integer) (just examples). You can generate the SQL query in VBA this way:
...
Dim strSQL as String
...
strSQL = "SELECT * FROM tblMyData " & _
"WHERE month='" & ComboMonth.Value & "' " & _
" AND year=" & ComboYear.Value ";"
...
[Form_Main Form].RecordSource = strSQL
[Form_Main Form].Requery
...
Hope this helps you.
Open the form in a different way.
DoCmd.OpenForm "MyForm",,,"MyYear=2013"
Or
DoCmd.OpenForm "MyForm",,,"MyYear=" & Me.MyCombo
Assuming that MyYear in the table or query is numeric. If it is not, you can use single quotes.
The general idea is that you use a form with all records, and use the Where argument of OpenForm to specify the records that should be shown. You can do the same with reports.
I have only a vague idea about what you're trying to accomplish. It might help to show us the SQL from Main_Form_Query. Meanwhile, consider whether you can use the form's .Filter property to do what you need.
If the form's Record Source includes a text field named fiscal_year, you could filter the rows displayed based on the year selected in your combo box.
Private Sub Combo1_AfterUpdate()
' .Value is the default property, so not required after Me.Combo
Me.Filter = "fiscal_year = '" & Me.Combo1 & "'"
Me.FilterOn = True
End Sub
Yet another approach could be to reference the combo value in Main_Form_Query.
WHERE
Forms!YourForm!Combo1 Is Null
OR some_field = Forms!YourForm!Combo1
Then do Me.Requery in the combo's After Update event.