Modules & VBA :: 2nd Run Of A Function Calculates Wrong Results?
Jul 21, 2014
i am using the following function in a query:
Code:
Public Function Progress(ByVal varCompany As Variant _
, ByVal varPercent As Variant) As Variant
Static varCompanyOld As Variant
Static varValueOld As Variant
Dim Value As Variant
If varCompany & vbNullChar = varCompanyOld Then
Value = (1 + varPercent) * varValueOld
varValueOld = Value
[code]....
This function is working if I use it with two or more companies.If I have only one company, it works at the first (query) run, too.But with the same company, a second (query) run calculates different results.
I think it is because of this condition:
Code:
If varCompany & vbNullChar = varCompanyOld Then ...
If the company name is e.g. Microsoft
At the first run of the query:
Microsoft & vbNullChar = "" -> wrong
The Else calculation will be carried out.
-> That is right for the first datapoint of a company
At a second run of the query:
varCompanyOld is saved as Microsoft & vbNullChar, so:
Microsoft & vbNullChar = Microsoft & vbNullChar -> True
The main calculation will be carried out.
-> That is wrong for the first datapoint of a company
I'm trying to do a string compare between two variables. One string variable is part of an array (which I'm looping through), the other is passed to the function as an argument.the function should return the position of a field in the OrderBy string of a subform.Here's the VBA :
Code:
Private Function SortPosition(strOrderBy As String, strField As String) As StringDim arrSortedFields() As String Dim i As Long If Len(strOrderBy) > 0 And InStr(strOrderBy, strField) > 0 Then arrSortedFields = Split(strOrderBy, ",")
[code]....
The weird thing is, the line in blue returns True when, by watching the variables, it appears that it should not, and returns False when it appears that it should?
I would have thought the expression "[RandomField]" Like "[RandomField]*" should return True?And similarly the expression "[SomeFieldName]" Like "[ADifferentField]*" should return False?Have been using 'Like' for donkey's years and never seen it throw results like this before?
(P.S. The reason I need to use 'Like' rather than a straight = is to account for the possibility that a field may be sorted descending, and therefore to nullify the DESC keyword which may follow any given field...)
I am trying to use the Environ Username function, which i have working! But i want to compare the result with a Username Table to determine if they have access etc...
I have answered my own question so I thought I would share as I couldn't find the solution in any posts. I confess that I don't understand why my results were wrong, but I managed to get them right. :rolleyes:
When using Dcount in a query, I was getting results which did not match the query results. For instance:
Phase_2: DCount("Project_Phase_ID","tbl_Prj_Details","Project_Phase_ID = 2") gave an answer of 27 when there were in fact 41 projects in that phase.
Searching the forum I came accross this:
Count() always counts the entire domain.
So, Dcount is not counting the record set of my query but something else. I have 4 tables in the query and no idea what domain my dcount was looking at. I presume the various join types were messing with it somehow. :confused:
To get round this, I stripped out the Dcount expressions and changed the query to a make table. I then used the created table as the basis of a query in which I had my Dcounts. The dcount results now agree with the query recordset. :) :) :)
Any background on the bits I clearly don't understand will be gratefully received. I hope this helps someone else sometime.
I have two tables Contacts & Allowance. There is a relationship defined between the two based on Contact ID (primary field/contacts - foreign key/allowance). The Contacts table has Firstname + Surname. I have produced a query based on certain fields in both tables however the result is totally pulling incorrect info.
Dear all i have a problem that i don't know what to do with it? Here it is: i have a cost table in which FO cost is saved.This FO cost is used in different calculation, in different forms. so i create a function called get_FO_cost() as below.
Function get_FO_cost() Dim s As String Dim c, r As Object Dim v As Single Set c = Application.CurrentProject.Connection Set r = CreateObject("ADODB.Recordset") s = "select FO_Cost from Cost_table where month = '" & Me![month] & "'" r.Open s, c, 1 If r.RecordCount <> 0 Then v = r![FO_cost] End If r.Close Set c = Nothing get_FO_Cost = v End Function
when I use this function for calculation then it returns wrong value. for Example: the value in the table for FO_cost = 0.005 ( it has a datatype single in table) then the value in form for this 25 * get_FO_Cost() = 0.124999997206032 but actually 25 * 0.005 = 0.125
when i debug the function code it shows FO_cost value 0.005, but when the debug is over the calculated value i.e. 25 * get_FO_Cost() is 0.124999997206032
I'm working on a select query that I have created through the visual query design window in Access 2003, I have multiple criteria but the query is not filtering the results properly.
I'm selecting only records :
where the DeliveryCountry field is within the EU - works where the ProductID does not contain Repair, Upgrade or Rpr - doesn't work where the Demo/Sale ID is 2 - works
I've viewed the code in SQL view but I still can't locate the problem, though I suspect it lies in the treatment of ANDs and ORs.
The SQL is pasted below (I have reformatted with indentations so I hope it is easier to read).
One thing to note: the reason the countries list is split in two is because Access did this automatically when I had one long list. Is there a maximum length for WHERE clauses?
FROM Products RIGHT JOIN (([Demo/Sale] RIGHT JOIN Orders ON [Demo/Sale].[Demo/SaleID] = Orders.[Demo/SaleID]) LEFT JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID) ON Products.ProductID = [Order Details].ProductID
WHERE (((Orders.OrdDeliveryCountry)="Austria" Or (Orders.OrdDeliveryCountry)="Belgium" Or (Orders.OrdDeliveryCountry)="Cyprus" Or (Orders.OrdDeliveryCountry)="Czech Republic" Or (Orders.OrdDeliveryCountry)="Denmark" Or (Orders.OrdDeliveryCountry)="Estonia" Or (Orders.OrdDeliveryCountry)="Finland" Or (Orders.OrdDeliveryCountry)="France" Or (Orders.OrdDeliveryCountry)="Germany" Or (Orders.OrdDeliveryCountry)="Greece" Or (Orders.OrdDeliveryCountry)="Hungary" Or (Orders.OrdDeliveryCountry)="Ireland" Or (Orders.OrdDeliveryCountry)="Italy" Or (Orders.OrdDeliveryCountry)="Latvia" Or (Orders.OrdDeliveryCountry)="Lithuania" Or (Orders.OrdDeliveryCountry)="Luxembourg" Or (Orders.OrdDeliveryCountry)="Malta") AND (([Order Details].ProductID) Not Like "*Upgrade") AND ((Orders.[Demo/SaleID])=2)) OR (((Orders.OrdDeliveryCountry)="Austria" Or (Orders.OrdDeliveryCountry)="Belgium" Or (Orders.OrdDeliveryCountry)="Cyprus" Or (Orders.OrdDeliveryCountry)="Czech Republic" Or (Orders.OrdDeliveryCountry)="Denmark" Or (Orders.OrdDeliveryCountry)="Estonia" Or (Orders.OrdDeliveryCountry)="Finland" Or (Orders.OrdDeliveryCountry)="France" Or (Orders.OrdDeliveryCountry)="Germany" Or (Orders.OrdDeliveryCountry)="Greece" Or (Orders.OrdDeliveryCountry)="Hungary" Or (Orders.OrdDeliveryCountry)="Ireland" Or (Orders.OrdDeliveryCountry)="Italy" Or (Orders.OrdDeliveryCountry)="Latvia" Or (Orders.OrdDeliveryCountry)="Lithuania" Or (Orders.OrdDeliveryCountry)="Luxembourg" Or (Orders.OrdDeliveryCountry)="Malta") AND (([Order Details].ProductID) Not Like "*Repair") AND ((Orders.[Demo/SaleID])=2)) OR (((Orders.OrdDeliveryCountry)="Austria" Or (Orders.OrdDeliveryCountry)="Belgium" Or (Orders.OrdDeliveryCountry)="Cyprus" Or (Orders.OrdDeliveryCountry)="Czech Republic" Or (Orders.OrdDeliveryCountry)="Denmark" Or (Orders.OrdDeliveryCountry)="Estonia" Or (Orders.OrdDeliveryCountry)="Finland" Or (Orders.OrdDeliveryCountry)="France" Or (Orders.OrdDeliveryCountry)="Germany" Or (Orders.OrdDeliveryCountry)="Greece" Or (Orders.OrdDeliveryCountry)="Hungary" Or (Orders.OrdDeliveryCountry)="Ireland" Or (Orders.OrdDeliveryCountry)="Italy" Or (Orders.OrdDeliveryCountry)="Latvia" Or (Orders.OrdDeliveryCountry)="Lithuania" Or (Orders.OrdDeliveryCountry)="Luxembourg" Or (Orders.OrdDeliveryCountry)="Malta") AND (([Order Details].ProductID) Not Like "*Rpr") AND ((Orders.[Demo/SaleID])=2))
OR (((Orders.OrdDeliveryCountry)="Holland" Or (Orders.OrdDeliveryCountry)="Poland" Or (Orders.OrdDeliveryCountry)="Portugal" Or (Orders.OrdDeliveryCountry)="Slovakia" Or (Orders.OrdDeliveryCountry)="Slovenia" Or (Orders.OrdDeliveryCountry)="Spain" Or (Orders.OrdDeliveryCountry)="Sweden") AND (([Order Details].ProductID) Not Like "*Upgrade") AND ((Orders.[Demo/SaleID])=2)) OR (((Orders.OrdDeliveryCountry)="Holland" Or (Orders.OrdDeliveryCountry)="Poland" Or (Orders.OrdDeliveryCountry)="Portugal" Or (Orders.OrdDeliveryCountry)="Slovakia" Or (Orders.OrdDeliveryCountry)="Slovenia" Or (Orders.OrdDeliveryCountry)="Spain" Or (Orders.OrdDeliveryCountry)="Sweden") AND (([Order Details].ProductID) Not Like "*Repair") AND ((Orders.[Demo/SaleID])=2)) OR (((Orders.OrdDeliveryCountry)="Holland" Or (Orders.OrdDeliveryCountry)="Poland" Or (Orders.OrdDeliveryCountry)="Portugal" Or (Orders.OrdDeliveryCountry)="Slovakia" Or (Orders.OrdDeliveryCountry)="Slovenia" Or (Orders.OrdDeliveryCountry)="Spain" Or (Orders.OrdDeliveryCountry)="Sweden") AND (([Order Details].ProductID) Not Like "*Rpr") AND ((Orders.[Demo/SaleID])=2))
So I created a search form which filters my results. Apparently I don't have enough posts to link to the source of the code though. The code is from this website, /forums/showthread.php?t=188663
I then wanted to allow users to double click a result in the listbox to take them to the form which contains details about that record, however the listbox doesn't point to the correct record.
-When nothing is specified in the search field, all records are shown in the listbox, but double clicking on the first record takes me to a form that has no information. Clicking the second record takes me to the Detail Form of the first record. -When information is put into the search field, the results are filtered and only a few display, however clicking the first result again takes me to a blank form while the second result takes me to the first record of the unfiltered list. There is no way to reach the Detail Form for the last result of the listbox. -I tried right clicking the results in the listbox and copy pasting the information. The first result gave me a "0", the second a "1", and so on and so forth. This was the same whether or not the information was filtered or not. -I tried switching to a combo box and got the same results.
I have an unbound combo box that I set up in a form using the combo box wizard in Access 2010. I selected the option that says, "Find a record on my form based on the value I selected in my combo box." The problem is that the combo box will not always display the correct record. It seems to only display the first record of a group of similarly named records in a table.
Example:
Code: Last Name First Name SSN Smith Alex 123-45-6789 Smith Jane 234-56-7891 Smith Mary 345-67-8910
If I select Smith Jane, the record for Smith Alex will display. I know that this has something to do with the bound column property, but I am unsure what to do to fix the issue.
What I have tried: I tried setting the primary key as the first field, but then I could only search by the primary key, which is unrealistic for this database. Users will be searching based on last name. How do I make the combo box select whichever record I select from the drop down list?
I have a query that currently calculates a rating based on various values entered into the database. This rating corresponds to a Quality Index value based in another table. I tried to set up a query that links the rating value in the query to the Rating in the table, however, when I run this query, I don't get all the results I should. Is there some other way to make this work? I thought it would be simple to link the rating value that is calculated to the rating in the table and have it report the Quality Index value associated with that value. Please help! :confused:
Item: Access app front end for an SQL database (production tracking/job logging utility)
Problem: The app has a main search page that allows job entries to be located and opened by varies criteria (job#, job name, etc). I can currently run multiple searches on different criteria successfully but if I open a job window(which has been returned as result of my search) and then close that job window to do a new search my search function will no longer return any results(other then “Calculating….”) unless I close out the access app and reload.
Thanks in advance for any ideas that can point me in the right direction to hunt down my bug.
I am building a report and need to know the coding in the query (or in the report) to achieve the following.
Currently, in my query - 3 fields that work fine:
AppDate - dates of set appointments (Appt)
MonthNo: DatePart("m",[App_Date]) - get Month value
YearNo: DatePart("yyyy",[App_Date]) - get Year value
What I need is : EXACT coding to get these counts to show in my report:
January 2013 12 appointment (there were a count of 12 appts in January) over 23 days (there were 23 days where appts were booked in January) of 31 days (total number of days in the month of January)
February 2013 18 appts (there were a count of 12 appts in February ) over 19 days (there were 23 days where appts were booked in January) of 28 days (total number of days in the month of February )
I'm a Access novice trying to set up a table to record the answers to simple yes/no questions. I've got all the questions set up and yes/no fields set for their responses, but I now want to add a field that calculates the percentage of yes responses on that particular report and record that too. I'm trying to use the 'calculated' data type, but then I can't work out what to type as the expression.
I am finishing up a database that logs basic activities/tasks for my coworkers. As they go in to the database and log an activity in it stays open until they end their day or they start a new task. All this works fine, but the problem comes when I try to determine the total time spent (in hours) on each activity/task. I have written similar queries before and they worked just fine, but for some reason I am having trouble getting this one to work. Here is the expression I'm using...
Time Diff (in hrs): DateDiff("h",[Sample_TM_Table_1]![Time_In],[Sample_TM_Table_1]![Time_Out])
Unfortunately, say Time_In = 8:32:38 am and Time_Out = 8:33:03 am The expression says that is equal to 946632.
For another Time_In = 8:33:00 am and Time_Out = 3:18:19 PM. The expression says this equals 946639.
I have tried changing the format of the date/time in both Time_In and Time_Out fields to ensure they were the same and cross checked the expression but still get the same answers each time. Even when I try to use "n" for the interval or "s" it is still highly incorrect. The only thing that makes me think I still have a formatting issue is that the Time_In shows a long date on the results table while Time_Out shows it in a general date format. However, when I go into both the table and the queries to check the formatting they both show general date. Any ideas? I'm all out! Thanks in advance.
I have a cool little form for the use of the organization's treasurer wherein she enters checks and deposits. I have a query that generates a running sum, so each line in the accounting report based on the table has the account total as of that date. The query behind the report is exactly what I want and is in the correct order. For example, the four transactions for 9/15/2014 are in the order entered, and the line total is correct. The report insists on listing the 4 in the example in some other order with or without OrderBy specified. With code from someone, perhaps on this forum, I added the following to the OnPage event:
Code: Private Sub Report_Page() Const TWIPSPERINCH = 1440 ' Offset from right edge of Control where our ' Vertical Line will start - adjust as you desire. ' Expressed in Twips Dim intLineMargin As Integer
[code]....
The result is a beautiful report (albeit in the wrong order) with vertical lines all the way to the bottom of the page.If I remove the OnPage code, the report is still in the wrong order, so obviously that wasn't the problem. OK, I think it is corrupted. I open a new db, import all into it. Still in wrong order. So next, I begin to recreate the report from scratch. Hooray! Right order! But I still want the vertical lines between the columns. So now, I copy the OnPage code and paste it into the new report's OnPage code. I get error message: "Compile error: User-defined type not defined" with the line "Dim MIPSstr As udtPrtMips_str" highlighted. Ok, I delete all of it and reenter it line for line manually, leaving out the comments. Get the same error message. After trying to research it, the only suggestions were to add Activex reference which can't be the problem, because the other version of the report doesn't throw an error and both are in the same db.
I have attached a clip of the report and a clip of the underlying query. As you can see in the first capture.png, the check numbers are in the wrong order and the amounts in the Total line don't sync with the total above adjusted by the amount on that line.
I have 2 controls on a form cmbFed and cmbState both are formatted as fixed with decimal places as 2. They display the correct values. cmbFed = .18 cmbState = .06 When I add a new control to add the 2. =[cmbFed]+[cmbState] result is .18.06 instead of .24 It looks like it is treating them as text. I even tried to do it in code Me.text639 = Me.cmbFed + Me.cmbState with the same results. It must be something simple I am missing a format for text639?
I am trying to check for when a user trys to enter a duplicate number.
The control that I am checking is in a subform on the main form:
Main: frmCandidateInfo Sub: frmTestInfo
Control on the subform is: RankOrder
I am trying to check the control entry against the table entry:
Table: tblTestEvents Field: RankOrder
Here is what I have:
Code: Private Sub RankOrder_BeforeUpdate(Cancel As Integer) Dim lngRankDup As Long lngRankDup = Nz(DLookup("[RankOrder]", "tblTestEvents", "[RankOrder]=" & Forms!frmCandidateInfo!sfTestInfo!Form!RankOrder, 0)) If lngRankDup <> 0 Then MsgBox TestEventID & " already exists in the database" End If End Sub
I know that the error is due to the argument not being correct, but I am not sure how to fix it.
I am writing the following query to insert data in tblpostroom from another table. Both the tables have same field names like Date1,582,1810.Now If I run the following query then in the fields 582,1810 of tblpostroom , the data gets stored 582,1810 respectively for all the records. But in actual fields 582 and 1810 store different data.
Code: INSERT INTO tblpostroom ( Date1, 582, 1810 ) SELECT Date1, 582, 1810 FROM Sheet1;
I have a field that is pre filled in with a value. The name is "Business".Then there is a combo box with various values. If the user would select a value that does not match with values that can be selected if in "business" a value is selected, it should show a message that the selection is wrong and user needs to select the correct one.
Example:If in the field "Business" the value "Food" is selected, then the possible values to be selected in the combobox would be: Fruit or Meet or Fast Food. If the value in "Business" would be "Wood" only selections could be made: Talble or Chair or Cabinet.So, if a user select "Food' in "Business" and in the combo box "Chair", it should show a message that the wrong selection was made and don't let them use the wrong one.
I am opening an excel file from access and changing the formatting from "dd/mm/yyyy hh:mm" to number with 15 decimal places.Then I am linking the file to the database and subsequently doing a lookup on the date time on the access form against this table.The excel file when formatted from vba in access shows the wrong number
datetime = 03/05/2013 11:26 database number = 41397.4763888889 Excel file number = 41398.4763888889 (which would equal 04/05/13 11:26)
now if I do it manually then I get 41397.4763888889 or if the macro is in excel I still get 41397.4763888889.Also I have tested the code with manually editing the excel file and this works fine.
Code: Private Sub Command288_Click() Dim s As String Dim t As Integer Dim ws As Worksheet s = LaunchCD(Me) MsgBox (s)
[code]....
also this brings up a form and then I select the field required for the lookup and with the button is pressed the rest of the code runs as follows.
Code: Private Sub LoadData_Click() Dim w As String w = Forms![frmList1]![Combo0] w = "[" & w & "]" Dim dtA As String
I have what is probably a stupid question but I've been struggling with this one for a while. I have an ordering database which has an Orders table (containing Order ID, Date, Supplier etc) and an Order Line table within which I have a combo box for Product name, supplier, price, VAT rate, Line price etc. At the moment, I have the order line table as a subform within the Order form (run from the Orders table). The problem I'm having is the subtotal and total fields. At the moment these are in the Order Line table as I cannot figure out how to get these in the Orders table. In summary, can I make a calculated field in one table that calculates values from another table (linked by Order ID)?
I run a physical therapy office and patients come in for treatment either 3, 4 or 5 times per week. My database is used to track these frequencies (among other things).
I have 3 queries which count how many patients come in 5, 4 and 3 times/week.
In my main table I have fields called "how many 5's", "how many 4's" and "how many 3's".
I have tried to design an update query which will update those fileds in my main table to reflect the counts in the 3 queries mentioned above.
(I'm not using SQL view, I'm using the query design view)
In the "update to:" row, I use the Build function and locate the count I'm looking for.
Problem: when I run the query I get the error: Operation must use an updateable query.
When we browse through records in a subform we store the records in the database.When we want to delete a records for example the third record from the five records always the first records will be deleted. How can we delete the records where the cursor is at? When we are at the third record and press the delete button the third record from the list in the subform should be deleted.
Code:
Option Compare Database Dim FocusBln As Boolean Private Sub Identificeer() Me.[Datum Aangemaakt].Visible = True Me.[Datum Aangemaakt].SetFocus If Me.[Datum Aangemaakt].Text = "" Then