Access VBA to repeat a specific line of code - sql

I have tried searching for this, but cannot find anything quite like what I want to do... Funny, because I would think it would be pretty simple.
I have the following code:
Dim strSQL As String
Dim strSQL1 As String
strSQL1 = [Reports]![SMT_PULL_SHEET]![Text59].Value
strSQL = "INSERT INTO tblJobRecordID (Job, JobRev, JobDate, JobTime) VALUES ('" & strSQL1 & "', '" & Me!Text63.Value & "', '" & Format(Now(), "MM/DD/YY") & "', '" & Format(Now(), "h:mm AMPM") & "');"
DoCmd.RunSQL (strSQL)
This logs information for manufacturing products. The table tblJobRecordID creates a unique identifier by means of an autonumber field that acts as a way to serialize each product.
I want to run DoCmd.RunSQL (strSQL) a certain number of times based on a text box populated on a report.
The intention is to insert the same record into the table a certain number of times and give each record a unique identifier in the autonumber field.
I am familiar with loops and do not want to use this method if I can help it. Is there a simple command that tells Access to run a line of code a specific number of times?
Any help is very much appreciated. Thank you!

Dim strSQL As String
Dim strSQL1 As String
strSQL1 = [Reports]![SMT_PULL_SHEET]![Text59].Value
strSQL = "INSERT INTO tblJobRecordID (Job, JobRev, JobDate, PrintTime, LotQty) VALUES ('" & strSQL1 & "', '" & Me!Text63.Value & "', '" & Format(Now(), "MM/DD/YY") & "', '" & Format(Now(), "h:mm AMPM") & "', '" & Me!Text67.Value & "');"
DoCmd.SetWarnings False
For intCounter = 1 To [Reports]![SMT_PULL_SHEET]![Text67].Value
DoCmd.RunSQL (strSQL)
Next
DoCmd.SetWarnings True`
Easier than I thought to prove out the loop for this. Thanks gentleman!

Related

Access asking me to enter a parameter value

I'm running an SQL query through VB in Microsoft Access for form to add records to a table. However, it keeps asking me to insert parameter value, when they are already present in the form.
Private Sub AddPart_Click()
Dim strSQL As String
strSQL = "INSERT INTO Part VALUES (" & Me.IdPartPrimary.Value & ", " & Me.NamePartPrimary.Value & ", " & Me.BrandPartPrimary.Value & ", " & Me.ModelPartPrimary.Value & ", " & Me.FunctionPartPrimary.Value & ", -1, " & Me.FatherPartPrimary.Value & ", " & Me.ProviderPartPrimary.Value & ", " & Me.AmountPartPrimary.Value & ");"
DoCmd.RunSQL strSQL
End Sub
I already checked for spelling mistakes and there were none. Also, this happens with every field. If I don't insert a parameter value and cancel instead, the record still gets added, only after I close and reopen the table lots of times.
If fields are text type, need text delimiters - apostrophe will serve. I assume comboboxes have a number value from a hidden foreign key column. Value property does not need to be specified as it is the default.
With Me
strSQL = "INSERT INTO Part " & _
" VALUES (" & .IdPartPrimary & ", '" & _
.NamePartPrimary & "', '" & .BrandPartPrimary & "', '" & _
.ModelPartPrimary & "', '" & .FunctionPartPrimary & "', -1, " & _
.FatherPartPrimary & ", " & .ProviderPartPrimary & ", " & .AmountPartPrimary & ")"
End With
AFAIK, Access cannot execute multi-action SQL statements but SQL injection is still possible. If you want to explore use of Parameters in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?
Another alternative to avoid SQL injection is to open a recordset, use its AddNew method to create a new record, and set value of each field. DAO.Recordset AddNew

How do I run an append query in Access VBA to create a certain number of identical records based on a quantity in a field on the form?

first thanks for any help you can provide.
Below is the append query I'm working with - straight forward. On the same form I'm pulling the values referenced from, there is a field that holds a quantity. I want this quantity to be referenced to perform this append query that number of times. If the quantity in the field is 6, then I want the append query to run 6 times. I know this would be a loop, but I'm rusty and I cannot find any clear examples of this on stack or elsewhere on the web.
Thanks again,
Shawn
Code thus far:
Private Sub Command20_Click()
Dim strSQL As String
'*****Append record to table*****
strSQL = "INSERT INTO tblStructuresNoDAworking (StructName, State, Brand, Flavor_Sub, _
Type, Size, Bottles_Case, Entry_Date) VALUES ('" & Me.Text90 & "','" & Me.Text26 _
& "','" & Me.Text28 & "','" & Me.Text30 & "','" & Me.Text91 & "','" & Me.Text92_
& "','" & Me.Text93 & "', '" & Now() & "')"
DoCmd.RunSQL (strSQL)
End Sub
First, you should name your controls to have meaningful names.
Second, Now should not be casted to text and then to date as you do. Insert it directly:
& "','" & Me.Text93 & "', Now())"
Then, using a loop in DAO is much faster and cleaner. See the example here:
Insert multiple records with a date range in MS Access
which you easily could adopt to use your Me.ComboDeal.Value for the loop.
Figured it out. Shortened the number of fields for ease of testing.
Private Sub Command20_Click()
DoCmd.SetWarnings False
Dim strSQL As String
'Define Loop Count
Dim I As Integer
For I = 1 To Me.ComboDeal.Value
'**Append record to table**
strSQL = "INSERT INTO tblStructuresNoDAworking (Structure_Name) _
VALUES ('" & Me.Combo121 & "')"
DoCmd.RunSQL (strSQL)
Next I
DoCmd.SetWarnings True
End Sub

Increase speed of multiple inserts into Access DB from VBA Dictionary

I am attempting to take a VBA Dictionary and either:
Insert a new row into the database if it does not exist
Update the row if it does
While my current code works for this, it runs extremely slowly for the thousands of records I may need to update, and other solutions I have found on this site do not really achieve what I am after. Could anyone help me achieve this? My code so far is below:
Sub UpdateDatabase(dict As Object)
Dim Conn As Object, StrSQL As String, Rs As Object
Dim hmm As ADODB.Recordset
Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Conn.Open "C:\XXXX\cfrv2.accdb"
dictCount = dict.Count
counter = 0
For Each varKey In dict.Keys()
Application.StatusBar = Str(counter) & "/" & Str(dictCount)
counter = counter + 1
StrSQL = "SELECT * FROM `All SAMs Backlog` WHERE [LOCID] = '" & varKey & "'"
Set hmm = Conn.Execute(StrSQL)
If hmm.BOF And hmm.EOF Then
StrSQL = "INSERT INTO `ALL SAMs Backlog` ([SAM], [LOCID], [RTC Date], [CFR Status], [CFR Completed Date], [CFR On Hold Reason], [MDU], [ICWB Issue], [Obsolete]) VALUES (dict.Item(varKey)(0), '" & varKey & "', '20/12/2018', '" & dict.Item(varKey)(1) & "', '02/01/2019', '" & dict.Item(varKey)(2) & "' , '" & dict.Item(varKey)(3) & "' , '" &dict.Item(varKey)(4) & "' , '" & dict.Item(varKey)(5) & "')"
Conn.Execute (StrSQL)
Else
'Update the LOC in the table
StrSQL = "UPDATE `All SAMs Backlog` SET ([CFR Status] = '" & dict.Item(varKey)(1) & "', [CFR On Hold Reason] = '" & dict.Item(varKey)(2) & "', [MDU] = '" & dict.Item(varKey)(3) & "', [ICWB Issue] = '" & dict.Item(varKey)(4) & "', [Obsolete] = '" & dict.Item(varKey)(5) & "')"
Conn.Execute (StrSQL)
End If
Next
Conn.Close
End Sub
Any help is appreciated.
Either:
Write the content of the dictionary to a temp table, then run a query as described here:
Update or insert data in table
or:
Open [All SAMs Backlog] as a recordset, loop the dictionary to add or edit records as needed, then close the recordset.

Insert SQL from combobox/textbox selections

I'm trying to add a row of data into the table using the selections from comboboxes and the textlabel. The error I'm receiving is in regard to the insert statement. Is this the correct way to reference the values in a combobox or textbox? I'm inserting into a table that has an autonumber primary key. Any help would be greatly appreciated.
Private Sub addResult_Click()
Dim strSQL As String
strSQL = "INSERT INTO Results (Student_ID, Class_ID, Test_Type, Student_Score, Total_Score, Level)
VALUES ('" & Me.cboStudents.Column(0) & "',
'" & Me.cboTeacher.Column(0) & "',
'" & Me.cboTestType.Column(1) & "',
'" & Me.txtTotalScore.Value & "',
'" & Me.txtStudentScore.Value & "',
'" & Me.cboTeacher.Column(2) & "')"
CurrentDb.Execute strSQL
End Sub

How to ignore the Null values in Insert query in access

I have the Database table where the Table needs to be updated using a form.
However all the fields in the Form need not be mandatory to be filled.
I am Writing the Below VB code for inserting However I get an error stating that there is a syntax error in the statement.As i understand it is because of the Null Values in the Variable. I understand that I need to use DBNull.Value for all the null Values.
Here the Thing is there are too many fields to check if the value is null or not.
any body suggest if there is a way to do a mass check on the values entered to be null?
VBCode:
Dim StrSQL As String
Dim StrSQL1 As String
Dim tktID As Variant
Dim Assi As Variant
Dim reopened As Variant
Dim valid As Variant
Dim Reopenreason As Variant
Dim ReassignmentAG As Variant
Dim RBSCollab As Variant
Dim SMEconf As Variant
Dim Cloabag As Variant
Dim smeName As Variant
Dim Updat As Variant
Dim Closed As Variant
Dim iss As Variant
Dim ana As Variant
Dim res As Variant
Dim rVariant As Variant
' Assigining values
tktID = Ticket_number.Value
reopened = Ticket_Reopened.Value
valid = Valid_Reopen.Value
Assi = Assiginee.Value
Reopenreason = Reopen_reason.Value
ReassignmentAG = Reassignment_AG.Value
RBSCollab = RBS_Collab.Value
SMEconf = CkBxSMEConfirmation.Value
Cloabag = Collabarated_AG.Value
smeName = SME_Name.Value
Updat = Update.Value
Closed = Issue_Closed.Value
iss = Issue.Value
ana = Analysis.Value
res = Resolution.Value
rdate = Resolve_date.Value
'Insert values into the tables
StrSQL = "INSERT INTO Updates (TicketID,Assiginee,ReassignmentAG,RBSCollab,CollabAG,SMEconfirmation,SMEName,Update,IssueClosed,Issue,Analysis,Resolution,ResolveDate,TicketReopened,ValidReopen,ReopenReason) VALUES ('" & tktID & "','" & Assi & "','" & ReassignmentAG & "','" & RBSCollab & "','" & Cloabag & "','" & SMEconf & "','" & smeName & "','" & Updat & "','" & Closed & "','" & iss & "','" & ana & "','" & res & "','" & rdate & "','" & reopened & "','" & valid & "','" & Reopenreason & "' ) "
DoCmd.RunSQL StrSQL
thanks in advance for your help
I, too, setup my first Access database using lots of unbound controls and SQL statements for moving data around. But this is not the way to use Access. You should be using bound forms where the controls automatically know what the constraints are based on the table/columns they are bound to.
This means much less code for you to write (and maintain), future developers can look at your Access app and know what's going on because it will be done in the Access paradigm, and if you place as much logic into your tables/relationships as possible then if someone comes along and links to your ACCDB or opens the backend they could enter data without entering bad data.
So ultimately this is an XY problem. Get rid of all this code (especially DoCmd.RunSQL) and create a bound form. Put your validation logic in foreign keys, validation rules, and/or data macros in the table.
A simple solution to this problem could be just check for element's value before using in the inset query and if element's value is undefined than set with null.
Pass this value to database in the query.
Do this for each field:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Ticket_number.Value & "'")
Then instead of this:
VALUES ('" & tktID & "',...
Do this
VALUES (" & tktID & ",...
Or if you don't mind replacing nulls with empty strings:
tktID = Nz(Ticket_number.Value)
will do it.
Of course you should at least make sure no single quotes are in the stings, so even better:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Replace(Ticket_number.Value,"'","''") & "'")
After building the string for INSERT statment
strSql = "INSERT INTO tblmovimentiServizi ( msid, " _
& " msData, msIdDestinazione, msOraInizioServizio, msOraFineServizio, msAndataRitorno, " _
& " msOraVincoloEntrata, msOraVincoloUscita, msidAnagraficaAutomezzi, msServizioEseguito, msNoteCommenti) " _
& " VALUES ('" & rst!newid & "', #" & rst!msData + Me.g1 & "#, '" _
& rst!msIdDestinazione & "', #" _
& rst!msOraInizioServizio & "#, #" _
& rst!msOraFineServizio & "#, '" _
& rst!msAndataRitorno & "', #" _
& rst!msOraVincoloEntrata & "#, #" _
& rst!msOraVincoloUscita & "#, '" _
& rst!msidAnagraficaAutomezzi & "', " _
& eseguito & ", '" _
& rst!msNoteCommenti & "'" _
& ");"
I added
strSql = Replace(strSql, "''", "null")
strSql = Replace(strSql, "##", "null")
and it works.