How to use Excel Object Model in Access Query Expression? - ms-access

I am moderate to advanced user of Microsoft Excel, but very new to Microsoft Access (2010 version). What I am trying to do is use Excel functions in an Access Query Expression. So far, I've researched how to set Access to reference the Microsoft Object Model by going to Create/Module/Tools/References and then selecting the Microsoft Excel 15.0 Object Library.
From there, I went to my Query (Design View) and attempted to add an expression in the Field row to calculate the distance between two points. As a test, I typed:
Distance: Excel.WorksheetFunction.ACOS(50)
I thought this would work, but once I closed, saved the Query, and reran the Query I received the following error:
Undefined function 'Excel.WorksheetFunction.ACOS' in expression
I've done some Googling to determine why this isn't working, but have been unsuccessful. I'm not sure if Access allows you to reference Excel directly from the expression. Or, perhaps my syntax is incorrect.

Write a simple function in VBA (in Access) that calls the Excel function you want to use:
public function myTestFunction(x as double) as double
myTestFunction = Excel.WorksheetFunction.ACOS(50)
end function
Use this function in your query:
If you use the query design grid:
Simply write the function in a column and put the column name of the column that holds the input value as the argument. If you want to put an alias to the column, write the alias before and use :; something like this: columnAlias: myTestFunction([OtherColumn])
If you're writing your query using SQL:
Write your query as usual; use the function like any other function available in SQL:
select [OtherColumn], myTestFunction([OtherColumn]) as function
from [YourTable]

Related

the expression you entered contain invalid syntax in access query

I am trying to make a query. I don't type anything. I use only every formula by clicking in built-in function of access, but I get this popup error
The function iif requires the condition, iftrue, and iffalse to be separated with a comma, not a colon. Makr it look like this:
Iif(condition, ifTrue, ifFalse)

SSRS Comma-delimited list as Parameter value

I have a report in SSRS. My parameter allows multiple values. My query has in the WHERE statement:
WHERE AllDiag IN (#Diag)
My user should be allowed to enter something like Z34.83,R30.0,0000.
These are 3 different codes to search for, so technically it is looking for:
WHERE AllDiag IN ('Z34.83','R30.0','0000')
I've tried all kinds of things like making the parameter properties in the query properties an expression using =join(Parameters!Diag.Value,"','"), and even entering the list of codes with the quotes already, but nothing seems to allow this to work.
I even tried some split function to see if it searched for each separately but I'm not sure I even use it right since there seems there might be some function that should run before.
I'm out of ideas. Any help is greatly appreciated!
I'm assuming your dataset uses the WHERE clause as you stated
WHERE AllDiag IN (#Diag)
I'm also assuming that you cannot easily produce a list of available parameter values to choose from.
So to create a parameter that allows the user to manually enter a list of values simply set 'Allow multiple values' on #Diag parameter. The user then simply types each value and presses enter after each one.
Note there is no need for comma's just type them one by one pressing enter after each.
When SSRS sees a multi-value parameter being passed to a SQL statement using an IN clause, it converts this to dynamic SQL automatically including adding the comma's. If you trace the report using the SQL Profiler, you can see the SQL that is generated.
I thought I would share this with you all in case you may have had issues (like I did) with passing multiple values in a single parameter from your web page to a SSRS report.
NOTE: This is different from passing multiple parameters, each with its own value into a report. The later, there are plenty of examples on the web.
This is very usefull when you need to basically pass into your report's SQL command a list of values for your report's SQL command to use using a "special" function, and where you do not know the number of times the values may be required, as the user can choose anything from one value to 'n' values (but we will hit a limit, as I'll explain later). It's also useful for generating Excel row-by-row extracts from your website - say for Pivot table handling or charting later on.
Unfortunately using IN() on its own tricks a lot of people and they cannot figure out why it does not work. That's because if you define your report in SSRS to expect a parameter straight into the IN() function, the system literally places the value as a parameter in the function and tries to compare what is essentialy a parameter "data type" with your column's data type and you will get errors.
If your report has SQL similar to this ...
SELECT t.Col1, t.Col2, etc
FROM myTable t
WHERE t.myColumn IN (#myListOfValues)
where #myListOfValues is something like "'value1','value2','value3',..." it "may" work but I found passing such a string from ASP.net into SSRS did not work and there are technical issues with string handling from the ASP.net side plus a limit depending your system and browser.
To get around possible issues, create a function in your SQL Server database to receive a string of values delimited by a comma and allow the function to turn your list into a table. That way the table can easily be linked using SQL and passed as a sort of "parameter feeder" into your report's SQL or dataset.
So without babbling on too much lets start with code and an example:
Firstly lets create a special utility function that converts a list of values into a table, and by the way this function can be used within your projects to do exactly that - split strings delimited by something into a table for anything else.
Open SQL Server and create a new function using your normal right-click NEW function command. Something like this ...
CREATE FUNCTION [dbo].[fnMakeTableFromList](#List VARCHAR(MAX),#Delimiter VARCHAR(255))
RETURNS TABLE
AS
RETURN (SELECT Item = CONVERT(VARCHAR, Item)
FROM (SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM (SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(#List, #Delimiter,'</i><i>')+ '</i>').query('.')) AS a
CROSS APPLY [XML].nodes('i') AS x(i)) AS y
WHERE Item IS NOT NULL);
NOTE: the delimiter does not have to be a single character! Again useful for delimiting using keywords, etc.
Note the XML logic and conversion in the function? That is because ASP.Net is going to literally pass some HTML into SQL Server and we're going to use it to strip off the data we need into a table.
Run the function with some values to test:
SELECT * FROM dbo.fnMakeTableFromList ('a,b,c,d', ',');
You should see 4 rows of data returned ...
a
b
c
d
That is the results in a table.
Now use this function in your SQL Reporting Services report:
Here is my report as an example:
SELECT DISTINCT s.StudentID
FROM tblStudents s
LEFT OUTER JOIN dbo.fnMakeTableFromList(#StudentList,',') AS list ON list.Item = s.StudentID
WHERE (#StudentList IS NULL
OR #StudentList='')
AND (l.Item IS NULL
OR l.Item = s.StudentID)
Note my example also caters for reporting every student ID if there was no value passed at all. So report every student found in tblStudents or report those based on the list of student IDs given, delimited by a comma. When you run this directly in SSRS, you'll be asked for a parameter #StudentList. In there type what ever values you need separated by a comma, and you should only get those student IDs. If not, make sure the report works "stand alone" first before going over to the ASP side.
Once you are happy your report works, and the function in SQL Server works, then we are ready to code the ASP.net side of things:
In your ASPX code behind page (C#) we need to control what the list is and how to pass it over to SSRS. Because we are dealing with a LIST<> here, I am only going to illustrate the way to do using a LIST<> to mimic an array. As you know C# does not have array terminology like you have with VB.
So in your ASP.net page paste this code in your PageLoad event ...
protected void Page_Load(object sender, EventArgs e)
{
//get parameters from the URL list
string strStudentList = Request.QueryString["StudentList"];
//create a List of parameters and pass it over to the report
List<ReportParameter> paramList = new List<ReportParameter>();
paramList.Add(new ReportParameter("StudentList", strStudentList));
//run the report
ReportViewer1.ServerReport.SetParameters(paramList);
}
Of course some objects in here have to be defined in your ASPx page.
For example I use a master page and as you can see, I did all of this to create a mailing list for printing on special sticky label paper.
<%# Page Language="C#" MasterPageFile="~/rptsStudentAdministration/StudentAdminReports.master" AutoEventWireup="true" CodeFile="rptStudentLabels.aspx.cs" Inherits="rptsStudentAdministration_rptStudentLabels" Title="Student Mailing Labels" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<rsweb:reportviewer id="ReportViewer1" runat="server" font-names="Verdana" font-size="8pt"
height="800px" processingmode="Remote" width="900px">
<ServerReport ReportServerUrl="<%$ AppSettings:ReportServerURL %>" ReportPath="/rptsStudentAdministration/rptStudentLabels"></ServerReport>
</rsweb:reportviewer>
</asp:Content>
Make sure you are using these as well in your .cs file:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Reporting.WebForms;
And that's it folks!
CONCLUSION:
If you need to generate a report in SQL Server Reporting services that relies on users selecting none, one or many values to control the logic in the report, then think of passing them all as a single parameter and using a function to turn your values into a table for ease of SQL management. Once you have the SQL working, you should be able to generate the report easily in design mode and using the above ASPx logic, be able to pass all the values delimited by a comma into into your report. An added bonus is to HIDE the parameter in SSRS and that way the user does not have to see what values they chose, and you control the entire report being generated programmatically.
There are a lot of answers here which don't really point to the solution.
Problem: the #Parameter value is passed to SQL as a comma delimited NVARCHAR value, NOT a list of data values you can JOIN to or use WHERE clauses with. When passed to SQL Server via a procedure call the data type of your parameters is also lost.
Solution in SQL Server 2016+ is to use the build in "split_string" function which returns a list of values from a single delimited field.
DECLARE #Parameter nvarchar(max);
Select *
FROM [dbo].[MyTable] a
JOIN (Select [value] FROM string_split(#Parameter)) b
ON a.ID=b.Value
It may be necessary to CAST your value field depending on the data type you are expecting SSRS to pass through. For example DATE values may look like this:
DECLARE #Parameter nvarchar(max);
Select *
FROM [dbo].[MyTable] a
JOIN (Select CAST([value] as DATE) as [value] FROM string_split(#Parameter)) b
ON a.SomeDateValue=b.Value
In Sql Server 2014 or lower, you can use custom functions to separate delimited list into table rows. Many examples exists on MSDN and StackOverflow, here's very detailed blog post detailing the pros and cons of many methods.
Either method would work with Command Text and Stored Procedure data sets.
I second the answer from Canadean_AS that you should setup a multi-select parameter.
However, if for some reason you have a hard requirement to accept a single comma delimited string into #Diag, you can try the following in your query:
WHERE CHARINDEX(','+AllDiag+',' , ','+#Diag+',') > 0
Be aware that you may encounter performance issues if your where clause is filtering a large dataset with this function.
A more efficient option is to parse #Diag into a table of its own and join that table to the dataset in the FROM clause.

How to use Access 2013 Parameter Query within Query?

In Access 2013 db, I've written two queries.
A Query having Parameter
SELECT [par], IIf(Len([par])>=4,Left(([par]),4),"") AS first_part, IIf(Len([par])>=6,Left(([par]),6),"") AS second_part, IIf(Len([par])>=8,Left(([par]),8),"") AS third_part;
A Query without Parameter
SELECT par_list.par, IIf(Len(par_list.par)>=4,Left((par_list.par),4),"") AS first_part, IIf(Len(par_list.par)>=6,Left((par_list.par),6),"") AS second_part, IIf(Len(par_list.par)>=8,Left((par_list.par),8),"") AS third_part
FROM par_list;
I want to rewrite the second query with the first query. How ?
I want to use the first query as function within other queries. How ?
Most Access parameter query call examples use VBA. CAN we call parameter query within another query, WITHOUT using VBA?
Do use VBA for this. That is also what it is intended for, and it will save you a lot of trouble when debugging.

How Can I Perform Date Comparisons in Access 2013 Query Criteria?

I have a date field in my table, and I'm writing a query in Access 2013 to select all items where the date is between 7-days-ago and 30-days-in-the-future.
Currently, I've added the following as "criteria" under the date field:
>=Today()-7 And <=Today()+30
But I get the following error when I try to save the query:
I've tried using DateDiff (as I have in other scenarios) but it tells me that I'm not allowed to use that type of expression as criteria.
EDIT: This is an Access 2013 custom web app for SharePoint 2013, and all the available functions and syntaxes appear to be different from those available in a desktop database file.
You might be confusing with the Excel function named TODAY(). In Access it is called Date().
You can also use Between..And.
Between Date()-7 And Date()+30
Added In response to advice about using SharePoint:
I don't use SharePoint, but might guess that you need to specify the field explicitly:
fieldName >= Today()-7 And fieldName <= Today()+30
you might use brackets to make the statement clearer:
(fieldName >= Today()-7) And (fieldName <= Today()+30)

Use Variable data in Microsoft Access 2010 Data Macro

I am new to Access 2010 Data Macros!
In my database I have a function that returns the UserId of the current user. The function returns pubUserId (Public pubUserId as integer)
I have a Data Macro that writes a new record to a table. This works very well. I want to improve the macro by:
* including a call to this function to confirm pubUserId (I then know 100% who the user is!)
* write pubUserId to a field in the table. (This will then keep a record of who did what!)
How do I do the above two steps?
Your macro should RunSql, and your Sql expression should append the result of the pubUserId function at the end the SQL INSERT statement.
I created a query that returns the value of the function (1 row, 1 cell). Then I set the field to something along the lines of DLookup("UserID","ViewName"). Voila!