Read (lookup multiple criteria) records from database table, and Write to database table with matching criteria - vb.net

How do I replicate the equation below in Access Query or in VB.net code?
{=SUM(IF('Customer '!$G$3='Glass Fabrication'!$D$3:$G$3,IF("Hole"='Glass Fabrication'!$A$4:$A$15,'Glass Fabrication'!$D$4:$G$15)))*E3}
The above equation is what I use in excel to do Vlookup more than 1 value and returns a value that matches 2 criteria. (Now, this can go on forever, and have as many criteria as possible)
Now, I am working on VB.net to make a Quotation system with the MS Access database (.mdb).
I have a table that lists all products that have several identifiers with 4 different prices. For the simplicity, let's say I have 2 identifiers and 4 prices.
I have fields like Name Category as identifiers, and sample data looks like this.
Name Category Tier 1 Tier 2 Tier 3 Tier 4
Apple...Fruit............$2..........$2...........$1.7........$1.5
Apple...Juice............$1..........$1...........$.75........$.75
Orange..Fruit.........$1.8.......$1.8.........$1.5.........$1.3
Coke...Drink............$1..........$1...........$.75........$.75
User Input = Apple , Juice , Tier 1
I can make =Sum(If formula in excel to check for Name column to match selected value, then check the Category column to check the 2nd value, then check the 1st Row header for Tier 1 value and returns $1.
I am very new to Access Database, so I have a hard time how to replicate this. I have tried making a query, but it only "filters" such criteria, and doesn't return a value.
Ultimately, I would want a table/query called Shopping Cart that accepts user input such as "Apple, Juice, Tier 1" and 4th Column(read-only) would automatically calculate and find that Price of $1 by looking up those 3 things.
I have set up the shopping cart table already, and it works perfectly except I don't know how to include this read-only automatically calculated/vlookup column. (I am using DataGridView in VB.net to bind to a shopping cart table that takes 3 user inputs.)
What would be the best way to do this? Make Query in Access and make it calculate in the database itself or VB.net to handle the calculation and write into the 4th column everytime user inputs 3 values?

Try this SQL query in MS Access, provided your example data is saved as an Access table:
SELECT Table.Name, Table.Category, [Enter Tier],
IIF([Enter Tier] = 'Tier 1', Table.[Tier 1], IIF([Enter Tier] = 'Tier 2', Table.[Tier 2],
IIF([Enter Tier] = 'Tier 3', Table.[Tier 3], IIF([Enter Tier] = 'Tier 4', Table.[Tier 4], Null)))) As Price
FROM Table
WHERE Table.Name = [Enter Name] AND Table.Category = [Enter Category]
The Enter fields will pop up for user to fill as parameter requests when you open query. It would be better to use an Access form for user to fill unbound textboxes and command button opens query using textbox values. Form fields can replace above Enter fields.

Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
Here value3 is a constant value. To use objects(variables),
Dim row AS DataRow = DataTable.Select("ColumnName1 = '" & variable & "'").FirstOrDefault() was used.

Related

Retrieving Columns with count greater than 1 - Google Sheet Query

I'm using Google sheets, and I want to get the data from one sheet to another where I want only the columns with count > 1.
Let's say we have 3 columns A, B, and C. I tried the following (the first sheet name is "Form Responses 1"):
I thought about using a query in the second sheet as: =query('Form Responses 1'!A1:Z, "Select A having count (A) >1 union select B having count (B) >1 union select C having count (C) > 1"). But I got a parse error where it seems that union and having are not supported in google sheets query.
How can I achieve this (whether it's using query or any other Google sheets function that can work)?
More details:
The first sheet contains info about exercises conducted during a lecture and it gets its data from a Google Form (so the responses are fed in this sheet). Here is a screenshot of it:
Please note that the form is divided into sections. When the user selects the course, the attendance, the participation, and adds a comment, then they go to the next section, the next section will be based on the selected course, the newly opened section will have the exercise name and rating questions (the exercise name is a dropdown list with items that are prefilled and specific to the selected course). That's why, you can see that "exercise name" and "rate the exercise" columns are repeated because we have 2 sections in this form.
The second sheet should contain the data of a selected course only (either mobile dev or web dev) which can be achieved easily through a query with a where clause. But, in addition to that, it shouldn't contain the empty columns of "exercise name" and "rate the exercise" as they correspond to another section. So, it should have only one exercise name column and one rating column that correspond to the selected course. Here is a screenshot if we only use a query with where clause without removing the extra name and rating columns:
Here is a screenshot with the desired result:
Thanks.
why not use just:
=QUERY('Form Responses 1'!A1:Z, "select A,B,C,D,E,F,G where F is not null", 1)
Use "OR" condition
Eg:-
QUERY(Data!A:R,"select A, N, P where N>0 or P>0")
where A column has country and N, P columns have population values

User-entered number of pages to print in MS Access VBA

Is it possible to have a user enter the desired number of pages they wish to print onto a form, and be able to print "Page X of Y" on each page?
I have a small shipping label application that requires a dynamic number of labels to be printed for any given shipment, and is entered by the user.
The data used for the label information is returned from the following stored procedure
SELECT C1.CompanyName,
C1.Address1,
C1.Address2,
C1.City,
C1.Province,
C1.PostalCode,
C2.CustomerName,
C2.ShippingAddress1,
C2.ShippingAddress2,
C2.ShippingAddress3,
C2.ShippingAddress4,
C2.City,
C2.Province,
C2.PostalCode
FROM MyCompany_tb C1,
Customer_tb C2
WHERE C2.CustomerID = #CUSTOMER_ID
AND C2.InvoiceNumber = #INVOICE_NUMBER
This will produce a single record that includes my company "return address" information (C1), and pairs it with the the customer's shipping information (C2). The label(s) that get
printed need to print out "Box 1 of 3", "Box 2 of 3", etc, depending on the value entered by the user.
I found this article, but I would prefer to do this without creating a "temp table" in Access. Is something like this possible?
You need an additional table, but it can be a simple number table, with one LongInt column ID with numbers 1..n
Then use a cartesian product to get the number of records you want.
In VBA:
' lngNumRecords is the number entered by the user
TempVars.Add "NumRecords", lngNumRecords
The query:
SELECT YourQuery.*, "Box " & [tblNumbers].[ID] & " of " & [TempVars]![NumRecords] AS BoxNo
FROM YourQuery, tblNumbers
WHERE tblNumbers.ID <= [TempVars]![NumRecords]
There is no JOIN, so you get your main record replicated as many times as IDs are specified.
This assumes that YourQuery returns exactly one record.

Google Query Set Field As

What I'm trying to do is create compound table using Google Spreadsheets.
Works...
=query('Sheet1'!A:F, "select C")
Fails...
=query('Sheet1'!A:F, "select C,(C/D) as PerItemCost")
I'm trying to use the Query function because I'm being lazy. I'd rather not add a G field to Sheet1 that's C/D. If I forget to update it, my report sheet won't show the correct values.
Is there away to use the traditional (Select column & ' text ' & column) AS NewColumn in Google Spreadsheets?
I finally figured this one out after some time.
You'll use the following format:
Label Field 'Title',Field 'Title'
So, normally it's
=query(A:F, "Select A,B,C Label A 'Pinky', B 'Brain', C 'Narf'")
The output will be results with Column A labeled as Pinky, Column B labeled as Brain, and so forth.
For my use, I needed something far more complex as I'm calculating fields. So, I needed to reference not just the field, but the calculation I was applying to it. See example below.
Example:
=query(A:F,"Select Year(A),Month(A)+1,Day(A),C/D Label C/D 'Cost per Unit', Year(A) 'Year', Month(A)+1 'Month',Day(A) 'Day'")
I was hoping that Google would've made it more intuitive, but c'este la vie.

How to create calculated column with data from another list

I have the following situation: List A has two columns (Name, Amount) and in List B (Name) I want to add a calculated column which should be the sum of all entries in List A that have the same name as in List B. Example:
List A:
NAME Amount
L0011 100
L0011 50
L0020 234
So in List B I want the calculated column to show:
NAME Amount
L0011 150
L0020 234
How can this be done? Workflow (as soon as I add/mod an entry in List A, update List B) or something else? Thanks
lem.mallari's answer is a huge pain unless you can assume that the Amounts in List A never change, since it's not tracking whether an item has already been added to the sum. There is no way for a Workflow to iterate through a SharePoint list, which means there is no easy way to calculate the sum or average of multiple list items.
The correct way to implement this will will require some development. The SharePoint Developer Training (2010, 2013) will actually get you most of the way there: an event receiver should trigger when items are added or changed in Lists A and B that uses SharePoint's API to go through List A and average values by Name, then update all (or just affected) items in List B. Alternatively, you can use JavaScript to display the sum of all entries in List A that have the same name as the item in List B as long as all the data is displayed on your page. If you're handy with XPath and InfoPath, you could add List A as a secondary data source to List B's form and select only applicable items in List A to sum from.
But if we're talking Workflows, here's the "workflow only" method. This was tested and successful in 2010. Create custom List C with the following columns:
Title (string, mandatory, enforce unique values)
TotalItems (integer, mandatory, default 0)
Sum (number, decimal places however you want, mandatory, default 0)
Average (calculated, =IF(TotalItems=0,0,Sum/TotalItems)) (optional)
Replace the Name columns in Lists A and B with lookup columns pointing at List C. Delete the Amount column in List B, instead including the Sum column as an additional column. Add the following columns to List A, and ensure that users cannot change them directly. This can be restricted by making InfoPath forms or by making alternative view and edit forms.
AmountArchive (number, identical to Amount, default 0)
AmountHasBeenSubmitted (yes/no, default no)
Create a Workflow to run each time an item is created or modified in List A. Use these commands (I'm using a list for readability; it was getting ugly when formatted as code):
If Current Item:Amount not equals Current Item:AmountArchive
Set Variable:Item Count to (Data source: List C; Field from source: TotalItems; Find the List Item: Field Title; Value: Current Item:Name(Return field as: Lookup Value (as Text)))
Calculate Variable:ItemCount plus 1 (Output to Variable: ItemCount)
Calculate List C:Sum (similar settings as above; be sure to use Lookup Value (as Text) and not String!) minus Current Item:AmountArchive (Output to Variable: SumWithoutValue)
Calculate Variable: SumWithoutValue plus Current Item:Amount (Output to Variable: NewSum)
If Current Item:AmountHasBeenSubmitted equals No
Set AmountHasBeenSubmitted to Yes
Update item in List C (Set TotalItems to Variable:ItemCount; Set Sum to Variable:NewSum; Find the List Item in the same way of Field:Title; Value: Current Item:Name(Return field as: Lookup Value (as Text))
Else
Update item in List C (don't do anything to TotalItems; use the same logic to set Sum to Variable:NewSum)
Set Amount to Current Item:AmountArchive
This can't be done using calculated columns because calculated columns can only be used for columns on the same list.
Using SharePoint Designer Workflows you can just use Create List Item and Update List Item actions so that whenever a user adds a value for L0011 the amount will be added in another list's column which contains the previous amounts already.
Let me know if you need a more detailed answer for the SharePoint approach and I'll provide you a step by step instruction on what to do.
What about using the DSum function? https://support.office.com/en-us/article/DSum-Function-08F8450E-3BF6-45E2-936F-386056E61A32
List B
NAME Amount
L0011 =DSum("[Amount]","List A","[NAME]=''" & [NAME] & "'")
L0020 =DSum("[Amount]","List A","[NAME]=''" & [NAME] & "'")

Display text corresponding to Combobox selection in Microsoft Access 2010

I have a contact form and one of the fields in a the form is a Contact_Type_ID. This field is a number field which also corresponds to a text field in another table (e.g. 1 = expatriate).
When I cycle through the contacts, their Contact_Type_ID is 1, 2, 3... instead of Non-profit, CEO, Vice-president, etc. This is a problem because one has no idea what number 3 means.
I would like to a combobox that only displays the corresponding text.
I can't get the two columns and 0;1 format to work. My hunch is that it's because I'm drawing information from two different tables. I can generate the correct list, but then the main entry doesn't change as I cycle through the contacts to reflect the current contact's [Contact_Type_ID].
I can't edit any of the current tables because I am supposed to apply this application to a much larger scale database.
I also tried setting the SQL for the row source:
'Populate the connection combo box '
Dim typeSQL As String
typeSQL = "SELECT DISTINCT Contacts.[ContactTypeID], Contact_Types.[ContactType] " & _
"FROM Contacts, Contact_Types " & _
"ORDER BY Contact_Types.[ContactType];"
Me.cbo_ContactType.RowSource = typeSQL
However, I then have the same problem: the combobox won't update as I cycle through the contacts. I don't understand the difference between the rowsource and the controlsource. I feel that this distinction might be key here.
Assuming I understand correctly:
In the combo box properties, go to the Data tab.
Set the Control Source to Contact_Type_ID.
This means that when you go through the records, the combo box will correspond to the Contact_Type_ID field from your data.
Set the Row Source to "SELECT Contacts.[ContactTypeID], Contact_Types.[ContactType] FROM Contacts, Contact_Types ORDER BY Contact_Types.[ContactType];"
The Row Source indicates the data that the combo box has access to, which will help it determine how to display the control source value.
Set the Bound Column to 1
Set Limit to List to Yes
Now in the Format tab. Change Column Count to 2.
Next set the column widths to the 0;1 you mentioned in your question.
Now try looking at form view, and it should behave as you expected.
If it does not work, create a new control with these instructions.
As I understand your question, you have a form with contacts based on a table Contacts and that table contains a field called either Contact_Type_ID or ContactTypeID. You wish to display the description of the contact type from a table Contact_Types.
You do not need to join tables for your combo, it should be very simple. The key, as you suspected, is the Control source, which is the property that relates one table to another.
Control source : ContactTypeID '' or Contact_Type_ID, choose from the list
Row source : SELECT ContactTypeID, ContactType FROM Contact_Types ORDER BY ContactType
Bound column : 1
Column count : 2
Column widths : 0,2
As an aside, you can join tables in a combo and still set the first column to 0 and it will still work, it is all in the correct set up.