On my form I have a button which the user can click. It will then prompt the user with 3 input boxes, where the user can enter in the information that he wants to run a query on. I want the query to run based on the values that he enters into the 3 inputboxes, but I cannot seem to figure this out. The query is based on another table in my database. Here is the code I've written. It won't compile because I have too many arguments. This is probably because I don't know how to pass variables with the DoCmd.OpenQuery command.
Private Sub VariableQuery_Click()
Dim strProdCode As String
Dim strCampCode As String
Dim strMailDate As String
strProdCode = InputBox("Enter Product Code", "Product Code")
strCampCode = InputBox("Enter Campaign Code", "Campaign Code")
strMailDate = InputBox("Enter Mail Date", "Mail Date")
DoCmd.OpenQuery "contribution", , , "[PRODUCT_CODE]=" & strProdCode & _
"[CAMPAIGN_CODE]=" & strCampCode & "[MAIL_DATE]=" & strMailDate
End Sub
Any help is appreciated. The name of the query I am trying to run is "contribution". PRODUCT_CODE, CAMPAIGN_CODE, and MAIL_DATE are the names of the fields in the database and PRODUCT_CODE and CAMPAIGN_CODE are both text fields, and MAIL_DATE is a Date/Time field.
I don't know if there is a different way to do this but how I would approach the problem is by creating the SQL string
Dim strSQL As String
strSQL = "SELECT ... INTO ... " _
& "FROM ... " _
& "WHERE [PRODUCT_CODE]='" & strProdCode &"' AND [CAMPAIGN_CODE]='" & strCampCode & "' AND [MAIL_DATE]=#" & strMailDate & "#"
DoCmd.RunSQL strSQL
Things to note
When you have WHERE kind of clauses you have to qualify the values of the fields appropriately e.g. '' around strings, ## around dates and nothing around numbers
DoCmd.RunSQL I believe only runs actions queries e.g. UPDATE, DELETE etc. Plain SELECT are not action queries.
If you want to hide the warnings that popup there are two ways to do it, one is to use CurrentDB.Execute(strSQL) instead or to use DoCmd.SetWarnings(False) and DoCmd.SetWarnings(True)
Edit (Possible helpful links)
http://allenbrowne.com/tips.html
Building SQL strings in Access/VBA
You can Google "building sql strings in ms access" or some variation of that for more sources
Related
I'm trying to create in MS Access a pass trough query which will be connected to SQL server and use combo box from the form as a filter parameter in the WHERE statement part.
I know that connection and everything works because if I enter
SELECT * FROM mrch.Promo_Request_Base
I receive all the results.
Now when I try to enter something like
SELECT * FROM mrch.Promo_Request_Base WHERE mrch.Promo_Request_Base.Requestor_Name = 'UserABC';
then it also works.
It does not work for me if I enter SQL like this:
SELECT *
FROM mrch.Promo_Request_Base
WHERE (((mrch.Promo_Request_Base.Requestor_Name) = [Forms]![f_PromoRequest_VIEW_Header_001a]![Combo133]));
I also tried this:
SELECT *
FROM mrch.Promo_Request_Base
WHERE (((mrch.Promo_Request_Base.Requestor_Name) = [Forms]![f_PromoRequest_VIEW_Header_001a]![Combo133].Columns(0)));
[Combo133] has value 'UserABC' in it.
I would be very thankful if you could help me.
You don't.
Pass-through queries are passed to the data source as-is, and aren't parsed by Access at all. This means there's no way to use form-based parameters in a pass-through query.
Instead, use VBA to set parameters.
For how to do that, see How do I use parameters in VBA in the different contexts in Microsoft Access?. Specifically, the section on DAO applies to pass-through queries.
This also means you can't open the query for displaying. Use a form in datasheet view using VBA to set its own recordset instead. Do note that if a recordset requires parameters to be requeried, this can lead to trouble on sort/filter.
A pass-through query means it is executed server side. That server can no more go look into access and pull data then go and try and steal all your emails or financial data on your computer.
the simple solution then is to "process" or "evaluate" the expression BEFORE you send it to sql server. You can use the following:
Dim strSQL As String
strSQL = "SELECT * From mrch.Promo_Request_Base " & _
"WHERE mrch.Promo_Request_Base.Requestor_Name = '" & _
[Forms]![f_PromoRequest_VIEW_Header_001a]![Combo133] & "'"
With CurrentDb.QueryDefs("qryPass")
.SQL = strSQL
End With
' now code here to open form, or say launch report
DoCmd.OpenReport "rptPromoList", acViewPreview
Note that you have to ensure that the sql is formatted correctly for the server side.
So, in above, I am assume Requestor_Name is a text type of field. So,, that means you have to place quotes (I used single) around the expression. If that column you get from the combo box is a number, then the quotes are not required, and you would use this:
strSQL = "SELECT * From mrch.Promo_Request_Base " & _
"WHERE mrch.Promo_Request_Base.Requestor_Name = " & _
[Forms]![f_PromoRequest_VIEW_Header_001a]![Combo133]
So the other code would be the same - the only change in above was how I left out the adding of quotes (') around the expression.
Many thanks for your help.
At the end I did it differently. Im changing the PassTrough query via VBA :
Private Sub Command159_Click()
Dim db As dao.Database
Set db = CurrentDb
Dim qdf As dao.QueryDef
Set qdf = db.QueryDefs("q_PassThrough_VIEW_001a")
qdf.SQL = "SELECT * From mrch.Promo_Request_Last_Version_rpt_v " & _
"WHERE mrch.Promo_Request_Last_Version_rpt_v.F_Qtr_CD LIKE '" & _
[Forms]![f_PromoRequest_VIEW_Header_001a]![Combo145] & "%'"
qdf.Close
db.Close
Set qdf = Nothing
Set db = Nothing
End Sub
I am trying to print a separate pdf file (billing invoice) from a form for each record in my database.
Form to print: BillingInvoice-
Source for form: FamilySubDIscSubDIscGrand
Primary field: Fnum
I've tried taking code from here:
How to output multiple PDF files based on record in MS Access?
This is the code that code as I have tried to modify it:
Option Compare Database
Option Explicit
Private Sub PrintBtn01_Click()
Dim rsGroup As DAO.Recordset
Dim ColumnName As String, myPath As String
myPath = "C:\test\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT DISTINCT FNum FROM FamilySubDIscSubDIscGrand", _
dbOpenDynaset)
Do Until rsGroup.EOF
ColumnName = rsGroup!FNum
' OPEN FORM, FILTERING RECORDSOURCE BY COLUMN VALUE
DoCmd.OpenForm "BillingInvoice-", acViewPreview, , "Column='" & ColumnName & "'"
' OUTPUT FORM TO FILE
DoCmd.OutputTo acOutputForm, "BillingInvoice-", acFormatPDF, _
myPath & ColumnName & ".pdf", False
rsGroup.MoveNext
Loop
End Sub
I’m doing something wrong.
It is successfully saving the pdf’s with the FNums in sequence, but printing the individual records for each FNum, it is printing all the records. So I end up with:
FNum001.pdf (all records for db)
FNum002.pdf (all records for db)
Fnum003.pdf (all records or db)
...
But what I need is:
FNum001.pdf (individual record for FNum001)
FNum002.pdf (individual record for FNum002)
FNum003.pdf (individual record for FNum003)
...
If FNum is numerical, you should not surround the criteria value with single quotes, i.e. this:
"Column='" & ColumnName & "'"
Should become:
"Column=" & ColumnName
Also, unless you have a field on your form called Column, this should be changed to:
"FNum = " & ColumnName
I am converting my Access query to SQL view. One of the Access query has where condition where a user can input values
where table1.id=[Enter the ID of the user]
Is there a way to convert a query like this to T-SQL. It is important for me to leave the prompt as it is.
Well, first, there is little reason to convert to a pass-though query.
However, SQL Server cannot prompt you in access (or say a web site that uses SQL Server). So the GUI part must be created by YOUR web site, or say access client in this case.
It is usually best to build some prompt form with a button, since those automatic prompts that Access creates are VERY poor from a UI point of view.
As noted, it is VERY likely that you can just continue to use the access query.
However, if you need a pt query, then you use access code to ask/get the prompt value, and then add that to your query.
This will work:
Dim strSQL As String
Dim invoiceNum As String
strSQL = "select * from tblInvoices where invoiceNumber = "
invoiceNum = InputBox("enter Invoice Number")
If invoiceNum = "" Then Exit Sub
strSQL = strSQL & invoicenumber
With CurrentDb.QueryDefs("qryPassR")
.SQL = strSQL
End With
' now, docmd.OpenReport, or openform or
' whatever it is you wanted to do with the sql
However, as noted, for reports etc., I would build a nice form that allows the user to enter a value. The query prompts are pure torture to your users, and they are not user friendly at all.
Also, the above assumes that you going to open some report, or some such. If you need the data returned in a reocrdset, the use this:
Dim strSQL As String
Dim invoiceNum As String
dim rst As DAO.RecordSet
strSQL = "select * from tblInvoices where invoiceNumber = "
invoiceNum = InputBox("enter Invoice Number")
If invoiceNum = "" Then Exit Sub
strSQL = strSQL & invoicenumber
With CurrentDb.QueryDefs("qryPassR")
.SQL = strSQL
Set rst = .OpenRecordset
End With
And last but not least, as others suggested here, you should consider a stored procedure with parameters, as the above is subject to SQL injection.
I am created a journal program for an internship project and I am using a MS-Access Database. I am programming in VB.net. Now, I am trying to make it so that they can "Update" their journals, meaning that they click on their calendar date and it brings them to that journal if they have one for that date. If they have one for that date then it shows the title and journal text entry for that date. I want to make it so that any changes they have made to the journal (editing the textbox fields) are also changed in the database when they click the update button. Here's what i have so far
Private Sub COE_JournalBtn_Click(sender As System.Object, e As System.EventArgs) Handles COE_JournalBtn.Click
If DateTimePicker1.Value <> Nothing Then
If TitleTxt.Text <> "" Then
If JournalTextRtxt.Text <> "" Then
myConnection.Open()
Dim DatePicked As String = DateTimePicker1.Value
Dim cmd As OleDbCommand
Dim str As String
Try
MyJournalTitle = TitleTxt.Text
MyJournalText = JournalTextRtxt.Text
str = "UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
cmd = New OleDbCommand(str, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
Catch ex As Exception
MessageBox.Show("There was an error processing your request. Please try again." & vbCrLf & vbCrLf & _
"Original Error:" & vbCrLf & vbCrLf & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
myConnection.Close()
End Try
myConnection.Close()
End If
End If
End If
End Sub
Now my update string by itself is
"UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
Now, what happens, is absolutely nothing. No errorboxes come up. No messageboxes appear. The program doesn't freeze. And the database remains unchanged. What am I doing wrong? Is there an error in my code or something missing? Please help me because I really want to figure this out and i've been looking everywhere for a solution in VB.net and cannot find one that applies to me being that I am using MS-Access and NOT SQL.
Thanks in advance,
Richard Paulicelli
Use a parametrized query to avoid Sql Injection Attacks and quoting problems
str = "Journals SET JournalTitle=?, JournalText=? WHERE JournalDate=?"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#jounalTitle", MyJournalTitle )
cmd.Parameters.AddWithValue("#journalText", MyJournalText)
cmd.Parameters.AddWithValue("#journalDate", DatePicked)
cmd.ExecuteNonQuery()
Using parameters will free your code from that continue quoting that expose your code to an high chance of typing errors. And you don't have any problem with Sql Injection
You may have a problem with this part of your UPDATE statement:
"' WHERE JournalDate=" & DatePicked
If the Journals field, JournalDate, is Date/Time data type, surround the date string value with Access date delimiter characters (#).
"' WHERE JournalDate=#" & DatePicked & "#"
You can also convert your date string to yyyy-mm-dd format to avoid misinterpreting the date literal based on local.
I agree with the suggestions to use a parameter query for this instead. I'm just trying to help you understand why the original attempt may have failed.
This has taken me nearly 2 weeks and I don't know what else to do. I have a main form (UserSearch) that has a subform (TestUserSub). The associated table for both forms is tblusers.
very simple; on the main form (UserSearch) I have a ComboBox associated with the fields in the tblusers eg cmbid, cmbname, cmbdept and so on. All I want, is for a user to make a selection from any of these comboboxes and for the associated fields to display in the subform (TestUserSub). I have tried several different versions of code in the after update event in a couple of the ComboBoxes and nothing is happening in the subform or in other instances I get error message.
One example i have tried is filtering running an SQL command
Private Sub cmbid_AfterUpdate()
Dim strSQL As String
If IsNull(Me.cmbaccess) Then
Me.RecordSource = "tblusers"
Else
strSQL = "SELECT tblUsers.[Team Member_ID] FROM tblUsers " & _
"WHERE (((tblUsers.[Team Member_ID])= " & [form_testusersub].[txtid2]))& ";"
Me.RecordSource = strSQL
End If
End Sub
The above didn't work... Can someone please help me with this. I have a sample database that I have been working off of and by some very strange way, they have managed to do this same thing without calling any code. Is this possible?
I was able to figure out the code using the sample below
Private Sub yourcombobox_AfterUpdate()
Dim LSQL As String
If IsNull(Me.yourcombobox.Value) Then
Form_yoursubform.RecordSource = "tablename"
Me.yoursubform.Requery
requerysubform 'macro to requery the whole form
Else
LSQL = "select * from tablename"
LSQL = LSQL & " where field= '" & yourcombobox & "'"
Form_yoursubform.RecordSource = LSQL
requerysubform 'macro to requery the whole form
End If
End Sub
hope this helps.