Using VBA to create a dynamic query after importing a SQL database table in MS Excel - sql

This is a problem that has stumped me for a couple of days, and one I've been trying to work on. Unfortunately I very new to working on this stuff, and don't have a lot of resources trying to solve this problem, so if I am unclear or you have a question please post a comment about it.
The problem I am trying to tackle is this:
After getting external data from a SQL Server and having a table in a spreadsheet, say the is called Products, and has columns for productid (column A), productname (column B), supplierid (column C), and categoryname (column D). Is there a way to define a cell, say E1 where you use can use VBA to create a dynamic query. In this dynamic query you would enter some value of categoryname where it would query the table, and give you the results?

It is possible to perform a dynamic query without using any VBA.
Base your table on "From Microsoft Query" (under the "Get External Data" group on the Data tab). Build your query using the Query Wizard, selecting the table columns of interest. On the "Query Wizard - Filter Data" tab, where you would normally say a particular column must have a specific value, instead of the specific value, use just a question mark (for any and all columns that need to be used to filter). When you return your data to Excel, you will be prompted to "Enter Parameter Value" for each ? you used. Just click OK at this stage.
When the Excel "Import Data" dialog appears, click "Properties...". On the Definition tab click the button labelled "Parameters...". For each parameter, choose to "Get the value from the following cell" and to "Refresh automatically when cell value changes". Click the red arrow button (to select a cell) and click in the cell where each parameter will get its value from.
It's a good idea to have a label alongside each cell, and maybe special formatting for the data entry cell. The results table can be on the same worksheet as the parameter entry cells, when you enter a value in the entry cell, a new query will be run and the result will be displayed.

Here is a link that might help.
It goes into using VBA to filter.
I found it a while ago when I looked for something similar, hope it helps.

Related

MS Access: Dependent drop down combobox in Split form without affecting the rest? [duplicate]

This question already has an answer here:
How to query combo box of only current record/row in Access data entry form?
(1 answer)
Closed 1 year ago.
I am trying to make a dependent drop down work with my database here but it is giving me a hard time for different reasons that I will explain.
This is what I have:
A form called "tblOTS" (split form based on an actual "tblOTS" table):
As well as a table called "tblAlphaCode":
When looking at the property sheet for the "Alpha Code" combobox (actually called "strOTSAlphaCode") on my tblOTS form, this is what I have:
The current SQL statement under "Row Source" for this strOTSAlphaCode is:
SELECT tblAlphaCode.strAlphaCode, tblAlphaCode.strCategory,
tblAlphaCode.ID, tblAlphaCode.numSortingOrder
FROM tblAlphaCode
ORDER BY tblAlphaCode.strCategory, tblAlphaCode.numSortingOrder;
Basically, when user select an Alpha code in the drop down from "tblOTS" form, it adds the ID of the tblAlphaCodes into the actual tblOTS record.
My goal is to have the user select first a "Category" (here FASTENERS/HARDWARE ...) when adding/modifying an OTS record, and then have the "Alpha Code" drop down dependent on what category was just selected.
I first tried to changed the SQL statement using a WHERE condition on the category field, based on the form category field itself:
SELECT tblAlphaCode.strAlphaCode, tblAlphaCode.strCategory, tblAlphaCode.ID, tblAlphaCode.numSortingOrder
FROM tblAlphaCode
WHERE (((tblAlphaCode.strCategory)=[Forms]![tblOTS]![strOTSCategory]))
ORDER BY tblAlphaCode.strCategory, tblAlphaCode.numSortingOrder;
And created a strOTSAlphaCode.requery in my Form_Current event to update it everytime.
However, it affects the whole form itself as my control source is directly affected by my Row Source in this instance, and the form looks like this:
You can see that the drop down is working beautifully, however, all the fields that do not have the same category as the current record that I work on (FASTENER <> HARDWARE here), are missing their Alpha code (the second record is missing "O-RING" compared to the first picture from this post); this behavior is problematic!
I tried to find workarounds by changing strOTSAlphaCode into a simple text box only containing the Alpha Code ID, added an unbound text box on top with dlookup function to find the actual alpha code related to this ID, and an unbound combobox in between with the exact same SQL statement inside the Row Source Property, that would update the strOTSAlphaCode with some VBA ... not ideal right?? Ahaha. This is why I believe there is a simpler way that I am not aware of, but also I would like to use a "search as you type" code for this combobox later on and this solution was making it very difficult.
How can I make this work? I believe the answer is a simple/different SQL statement to put in my Row Source property, that is probably something related to some type of JOIN statement? Or something else? I expect to write some VBA code to make all of this work flawlessly, but I want to make sure that I have the right SQL statement first.
Thank you June7;
Yes, the link you gave me ( this link ) states 2 solutions, and the second one is the one that I talked about when describing my problem:
for forms in Continuous or Datasheet view, include lookup table in form RecordSource, bind a textbox to descriptive field from lookup
table, position textbox on top of combobox, set textbox as Locked Yes
and TabStop No
So I guess, the answer is that I MUST have a textbox with dlookup setup for my case; I put it on "locked" so that if the user wants to change it by typing in it, he will first have to select the arrow. This will work with what I wanted to do
Cheers,

Use date in Excel cell in SQL Query

How do I connect the Excel cell with the date to the SQL Query? I use Power Query. The Database is SQL Server.Please Help me.
Example of Query:
Select Account, Date
From Accountdate
Where Date = "Value in Excel cell"
Type a value into an Excel cell
Keep that cell selected. From the Power Query ribbon choose From Table.
Uncheck My Table Has Headers before clicking OK.
In the Power Query Query Editor, right click on that single value which you entered before and choose Drill Down
Click Apply & Close
In the Power Query, choose From SQL
Connect to your data source (don't worry about using the parameter yet.)
Once you're in the Query Editor with the correct SQL table being shown, choose the column you want to filter by your parameter. Go ahead and do a filter using the filter dropdown. Now change the formula bar and replace the number that you filtered by with the name of the query that you created in Step 5. That query by default will be called Table1 so your query in this step might look something like this: = Table.SelectRows(dbo_MySqlTable, each [ID] > Table1)
You will probably get a prompt asking you to classify the permissions to apply to each data source to make sure there are no security leaks. Once you've done that, click OK.
Click Apply & Close.

SSRS SQL report builder deleting column

I have a problem with SSRS report builder. Basically what I want to do is to delete a column. I have a report that someone else made and there is 1 column (xxx) that no longer exists in data source tables so I need to delete it.
When I go to query designer and delete this column from the code and run it there, it works. I close query designer window and see that list of columns (fields) is updated now and xxx column is not there. Then, I delete this column manually in designer (default screen) and when I try to run the report, It doesn't work:
"The Value expression for the text box ‘XXXDataField’ refers to the field ‘xxx’. Report item expressions can only refer to fields within the current dataset scope or, if inside an aggregate, the specified dataset scope. Letters in the names of fields must use the correct case."
But that field should be already deleted. So I don't know what else I can do, or what it can be linked to. I just want to delete it. Any Idea?
Thank you
If your dataset does not contain xxx but your DataTable has this error is normal
You either delete that column from your table or at lease delete DataSet Binding from table so that SSRS does not try to retrieve that column from DataSet
It will be a reference to the field in another field. For example, if you deleted a column that showed an OrderShipped status, then you might have another text box highlighted based on this.
The error is telling you which textbox is in error. So, click somewhere on the designer, then in the properties window, right at the top, click the dropdown which allows you to choose specific report items, choose XXXDataField (the one named in the error message) and then check the value expression. In there you will find the reference to the column you deleted.

Choose AS400 query records directly from Excel

I've been searching the internet for hours trying to figure out if the following is even possible:
To choose the AS400 query records directly from Excel.
I haven't found any solution or description of how this could be achieved, which makes me guess that it's simply not possible. However, I haven't seen anyone confirm that it is impossible.
So my question is: Is this possible? And if it is, could you point me in the right direction in order for me to start learning how to do it?
I know its possible to run a query from Excel, and then adding parameters via SQL statements, but in my case, this presents several problems that could be avoided by choosing the records before the query is executed.
Example:
I have a query with a column (lets call it ColVal) that can hold the values 1 and/or 2. In the AS400 program under the menu "Work with queries" and then "Choose records" I can specify which records the query should contain when it has run based on the value in ColVal. This means i can get three different situations (A, B and C) when i run the query:
A) The query only contains records where the value in ColVal is 1
B) The query only contains records where the value in ColVal is 2
C) The query contains records where the value in ColVal is either 1 or 2
The goal is to be able to choose which situation I want from Excel in order to circumvent opening and using the AS400 program.
However, using situation C and then editing the query in Excel with an SQL statement to mimic situation A or B is not an option, as this means the query still contains undesired records.
This whole thing boils down to the following: Is it even possible to run the query from Excel essentially changing the data it contains and not just outputting it to excel? If this is possible, is it then possible to pass a parameter to the AS400 system and use it to create situation A, B or C?
I hope this example makes sense.
Edit - New example
Say i have different customers A and B. I can open the AS400 program and run a query in which i have specified that I only want data on customer A. I can then open Excel and use filters (as Hambone described) on the query to determine which records I want to output. However, if I want to work with data from customer B, I have to open the AS400 again and run the query with different parameters. I would like to be able to "change" my dataset from customer A to B from Excel, without having to include both in my recordset and then filter out one of them.
I imagined this is doable if you could pass a parameter to the AS400. The AS400 then runs the query using this parameter as the criteria for which records should be stored in the query. This means that if the parameter is Customer B, then there is no way to acces data from customer A, without running the query through AS400 again.
Any ideas are greatly appreciated :)
Follow up to my comment, here is a quick primer on how to run an ODBC query directly in MS Excel using Microsoft Query. This is very different than Power Query, which you referenced, in that MS Query is standard with Excel -- it's not a plug-in. This is relevant because it means everyone has it. If you are deploying a solution to others, that's an important consideration.
To start an MS Query in Excel, go to the data tab, select "From Other Sources" -> "Microsoft Query."
A list of your ODBC connections will come up. Pick the one that you want and select "OK."
It may or may not ask you for a login (depending on which ODBC connection you use and how its configured).
The next part is important. MS Query is going to try to have you use its builder to create the query. If you have the SQL, skip this part. It's horrible. Click "Cancel" on the query wizard, and then click the "SQL" button to enter your own SQL. If you can, make sure the result set is small (like use where 1 = 2 in the query).
When MS Query returns results, click the button next to the SQL Button to have it return the results to the spreadsheet. It looks like a little door.
From here, any time you want to refresh the query, you can simply right-click the data table in Excel and select "refresh." Alternatively you can go to the data tab on the ribbon and select "Refresh."
By the way if you have linked pivot tables and charts, the "Refresh All" option will refresh those as well, in the correct order.
To edit your query at any time, right-click on the table in Excel, go to Table-External Data Properties:
Then Click on the Connection Properties icon (highlighted below)
Click on the second tab (Definition) and edit the SQL Directly.
Parameters can be declared simply by inserting a bare "?" in place of your literal.
In other words, if your query looks like this:
select *
from users
where user_id = 'hambone'
Just change it to:
select *
from users
where user_id = ?
Excel will prompt you for a user id before it runs the query. From here, you also have the option of putting the parameter value in a cell within the spreadsheet and having the query read it from there. You'll see these when you right-click the table and go to the "Parameters" menu option.
Let me know if this helps or is unclear.
-- EDIT 7/23/2018 --
To follow up on your latest edit, it is possible to handle the scenario you describe, where you want to be able to filter on a value, or if none is given, then not have a filter. You see this a lot when you present multiple filter options to the user and you want a blank to mean "no filter," which is obviously counter to the way SQL works.
However, you can hack SQL to still make it work:
select * from activities
where
(activity = ? or ? is null) and
(energy = ? or ? is null)
In this example you have to declare four parameters instead of two, two for each.
You might also have to play with datatypes, depending on the RDBMS (for example for numerics you might have to say ? = 0 instead of ? is null or even ? = '' for text).
Here is a working example where a single filter was applied on the query above and you can clearly see the second one did not have an impact.
Yes it's possible. You need to use an ODBC driver to connect to the AS400 and retrieve the data. The driver and documentation are Here

Is there any way use the values in a cell to query a SQL table and see if the value exists in the table?

I have an Excel spreadsheet containing all of my company's Vendor Codes. When a new code is added to this spreadsheet, we then add it to a configuration table within our database which allows us to accept that vendor. Right now I'm going through my Excel Spreadsheet and reviewing each section of code to find out if it exists in the SQL Table.
Is there any way use the values in a cell to query my VendorConfig table and see if it exists?
Spreadsheet Columns: VendorID, VendorCode, Config
You could use the "get external data" command to bring a value into a cell to check against. Alternatively, here is a link to a web post that has a cool answer to this problem (NOTE: I haven't actually tried this code but, from a quick glance, it looks right): Add formula to excel to validate data