I'm trying to set command buttons to enter data into a table. If the record already exists I want the button to update it, and if it does not the button needs to create it. Here's a sample of what the table looks like
ID scenarioID reductionID Impact Variable Variable Impact
1 1 1 Safety 4
2 1 1 Environmental 2
3 1 1 Financial 1
In order to accurately locate records, it needs to search for the specific impact variable paired with the scenarioID. I'm trying to use a select statement, but DoCmd.RunSQL doesn't work for select statements, and I'm not sure how else to do it.
Here's the code. I left DoCmd.SQL in front of the select statement for lack of anything else to place there for now.
Private Sub Var1R1_Click() 'Stores appropriate values in tImpact upon click
'Declaring database and setting recordset
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("tImpact")
'Declaring Variable as Scenario Choice combobox value
Dim Sc As Integer
Sc = Schoice.Value
'Stores impact variable
Dim impvar1 As String
'Desired impact variable for column 1
impvar1 = DLookup("impactVariable", "tImpactVars", "ID = 1")
DoCmd.RunSQL "SELECT * FROM tImpact WHERE [Impact Variable] = " & impvar1 & " AND scenarioID = " & Sc
If rs.EOF Then
DoCmd.RunSQL "INSERT INTO tImpact(scenarioID, [Impact Variable], [Variable Impact])" & "VALUES (" & Sc & ", " & impvar1 & ", 1)"
MsgBox "Record Added", vbOKOnly
Else
db.Execute "UPDATE tImpact SET [Variable Impact] = 1 WHERE [Impact Variable] = " & impvar1 & " AND scenarioID = " & Sc
MsgBox "Record Updated", vbOKOnly
End If
End Sub
If anyone can tell me how to get that SELECT statement to run, or another way of doing this, that would be great.
Any help is greatly appreciated!
You can use a recordset. In this case a recordset is better, since you only execute the SQL one time, if it returns a record, you "edit" and if not then you "add" with the SAME reocrdset. This approach is FAR less code, and the values you set into the reocrdset does not require messy quotes or delimiters etc.
eg:
scenaridID = 1 ' set this to any number
impvar1 = "Safety" ' set this to any string
updateTo = "Financial"
strSQL = "select * from tImpact where [Impact Variable] = '" & impvar1 & "'" & _
" AND scenaridID = " & scenaridID
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If .RecordCount = 0 Then
' add the reocrd
.AddNew
Else
.Edit
End If
!scenaridID = scenarid
![Impact Variable] = impvar1
![Variable Impact] = 1
.Update
End With
rst.Close
So you can use the same code for the update and the edit. It just a question if you add or edit.
Use OpenRecordset and retrieve the ID for the record if it exists.
Private Sub Command0_Click()
Dim aLookup(1 To 3) As String
Dim aAction(1 To 3) As String
Dim rs As Recordset
Dim db As Database
'Replace these two constants with where you get the information on your form
Const sIMPVAR As String = "Financial"
Const lSCENID As Long = 1
'Build the SQL to find the ID if it exists
aLookup(1) = "SELECT ID FROM tImpact"
aLookup(2) = "WHERE ScenarioID = " & lSCENID
aLookup(3) = "AND ImpactVariable = """ & sIMPVAR & """"
'Run the sql to find the id
Set db = CurrentDb
Set rs = db.OpenRecordset(Join(aLookup, Space(1)))
If rs.BOF And rs.EOF Then 'it doesn't exist, so build the insert statement
aAction(1) = "INSERT INTO tImpact"
aAction(2) = "(ScenarioID, ImpactVariable, VariableImpact)"
aAction(3) = "VALUES (" & lSCENID & ", '" & sIMPVAR & "', 1)"
Else 'it does exist, so build the update statement
aAction(1) = "UPDATE tImpact"
aAction(2) = "SET VariableImpact = 1"
aAction(3) = "WHERE ID = " & rs.Fields(0).Value
End If
'Run the action query
db.Execute Join(aAction, Space(1))
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Related
I have table named schedules where I should change values of some field depending value of another field
I manage to do that running code on form (record by record) but now I like to run it outside of form
because of mass import to database - Is it possible?
Here is part of my code:
If Not IsNumeric(DAY_0_DEST_0_NAME) Then
DAY_0_TYPE_0_OSP = 1
Else: DAY_0_TYPE_0_OSP = 3
End If
If Nz(DAY_0_DEST_0_NAME) = "" Then
DAY_0_TYPE_0_OSP = 0
End If
If Not IsNumeric(DAY_0_DEST_1_NAME) Then
DAY_0_TYPE_1_OSP = 1
Else: DAY_0_TYPE_1_OSP = 3
End If
If Nz(DAY_0_DEST_1_NAME) = "" Then
DAY_0_TYPE_1_OSP = 0
End If
Possibly the easiest way to do this is to run some update SQL statements from a VBA procedure. And because you are altering two pairs of fields, you can do this in a small loop:
Sub sUpdateData()
Dim db As DAO.Database
Dim strSQL As String
Dim lngLoop1 As Long
Set db = DBEngine(0)(0)
For lngLoop1 = 0 To 1
db.Execute "UPDATE Table1 SET DAY_0_TYPE_" & lngLoop1 & "_OSP=3 WHERE IsNumeric(DAY_0_DEST_" & lngLoop1 & "_NAME)=True;"
db.Execute "UPDATE Table1 SET DAY_0_TYPE_" & lngLoop1 & "_OSP=1 WHERE IsNumeric(DAY_0_DEST_" & lngLoop1 & "_NAME)=False;"
db.Execute "UPDATE Table1 SET DAY_0_TYPE_" & lngLoop1 & "_OSP=0 WHERE DAY_0_DEST_" & lngLoop1 & "_NAME IS NULL;"
Next lngLoop1
Set db = Nothing
End Sub
Regards,
I have a table, which was pulled out of some XML data. I'm trying to do a cross reference, so I can line out a plan for organizing the data. This 1 table has a list of variables. Fields of different data types, computations, as well as dialogs. One of the columns has options. If the data type of the variable is a dialog, its options has a list of variables, separated by a semi-colon.
So the main table has a structure like so:
For the dialog records I need to look through their options column and insert records into a normalized table. For each field, in that column, I want to add a record with that dialog name, and the ID of the row in that table (I added a PK to the table). For instance, in the dialog record, Options column, there is a field in there called BusinessName TE. I need to search this main table for the PK ID of the row that has a variable name of the same. I need to put that record's ID with the name of the dialog, and insert both into a new table I set up. This will create a cross reference for me, so I can know which variables are being used by which dialogs.
I appreciate any help anyone can give. I see stuff about using a split function, arrays and looping through to get each value, but the examples I'm finding are for strings, not a column in a table.
Thanks!
Edit: Adding in the VBA code I'm working with. I attached it to a button on a form, just so I could click to run it.
Private Sub RunParse_Click()
Dim db As DAO.Database
Dim rs As Recordset
Set db = CurrentDb()
Dim sqlStr, insertSQL, arrayVal As String
Dim TestArray As Variant
Dim Options As String
Dim Dialog As String
Dim FieldName As Long
Dim i As Integer
sqlStr = "SELECT [MASTER Fields].Options,[MASTER Fields].[Variable Name] FROM [MASTER Fields] WHERE ((([MASTER Fields].[Variable Type])='dialog'));"
Set rs = db.OpenRecordset(sqlStr)
rs.MoveLast
rs.MoveFirst
Do While Not rs.EOF
Options = rs.Fields(0)
Dialog = rs.Fields(1)
If InStr(Options, ";") Then
TestArray = Split(Options, ";")
For i = 0 To UBound(TestArray) - LBound(TestArray) + 1
If TestArray(i) <> "" Then
arrayVal = TestArray(i)
FieldName = DLookup("ID", "MASTER Fields", "[Variable Name] = " & "'" & arrayVal & "'")
insertSQL = "INSERT INTO FieldTemplatesUse(FID, TemplateAK) " _
& "VALUES(""" & FieldName & """, """ & Dialog & """)"
DoCmd.RunSQL (insertSQL)
End If
Next i
End If
rs.MoveNext
Loop
End Sub
right now on the line that says
If TestArray(i) <> "" Then
creates an error ""
If anyone can help, I'd really appreciate it!
Another Edit:
Parfait figured out my issue. I'm posting the final code I am using, in case it helps someone else! p.s. I added a condition to check if the dlookup is successful, and trap failures in a failures table. That way I can check those out afterward.
Private Sub RunParse_Click()
Dim db As DAO.Database
Dim rs As Recordset
Set db = CurrentDb()
Dim sqlStr, insertSQL, arrayVal As String
Dim TestArray As Variant
Dim Options As String
Dim Dialog As String
Dim FieldName As Long
Dim i As Integer
sqlStr = "SELECT [Master Fields].Options,[Master Fields].[Variable Name] FROM [Master Fields] WHERE ((([Master Fields].[Variable Type])='dialog'));"
Set rs = db.OpenRecordset(sqlStr)
rs.MoveLast
rs.MoveFirst
Do While Not rs.EOF
Options = rs.Fields(0)
Dialog = rs.Fields(1)
If InStr(Options, ";") Then
TestArray = Split(Options, ";")
For i = 0 To UBound(TestArray) - LBound(TestArray)
If TestArray(i) <> "" Then
arrayVal = TestArray(i)
If Not (IsNull(DLookup("ID", "Master Fields", "[Variable Name] = " & "'" & arrayVal & "'"))) Then
FieldName = DLookup("ID", "Master Fields", "[Variable Name] = " & "'" & arrayVal & "'")
insertSQL = "INSERT INTO FieldTemplatesUse(FID, TemplateAK) " _
& "VALUES(""" & FieldName & """, """ & Dialog & """)"
DoCmd.RunSQL (insertSQL)
'MsgBox "Adding ID = " & FieldName & "for Dialog: " & Dialog & "Now"
Else
insertSQL = "INSERT INTO tblFieldsNotFound(Dialog, FieldNotFound) " _
& "VALUES(""" & Dialog & """, """ & arrayVal & """)"
DoCmd.RunSQL (insertSQL)
End If
End If
Next i
End If
rs.MoveNext
Loop
MsgBox "All Done!"
End Sub
I have an array which can have a different amount of values, depending on the situation. I want to put these values as a parameter in a query in ms access.
The problem is, if I use the following code to generate a parameter, it sends the whole string as one value to the query, which obviously does not return any rows.
Do Until i = size + 1
If Not IsEmpty(gvaruocat(i)) Then
If Not IsEmpty(DLookup("uo_cat_id", "tbl_uo_cat", "[uo_cat_id] = " & CInt(gvaruocat(i)))) Then
If IsEmpty(get_uocat_param) Then
get_uocat_param = CInt(gvaruocat(i))
Else
get_uocat_param = get_uocat_param & " OR tbl_uo_step.uo_step_cat = " & CInt(gvaruocat(i))
End If
End If
End If
i = i + 1
Loop
At the moment I have 'Fixed' it by generating an SQL string and leaving the query out all together.
get_uocat = "SELECT tbl_product.prod_descr, tbl_uo_cat.uo_cat_descr, tbl_uo_step.uo_step_descr" & vbCrLf _
& "FROM (tbl_product INNER JOIN tbl_uo_cat ON tbl_product.prod_id = tbl_uo_cat.uo_cat_prod) INNER JOIN tbl_uo_step ON tbl_uo_cat.uo_cat_id = tbl_uo_step.uo_step_cat" & vbCrLf _
& "WHERE (((tbl_uo_step.uo_step_cat) = " & get_uocat_param & ")) " & vbCrLf _
& "ORDER BY tbl_product.prod_descr, tbl_uo_cat.uo_cat_descr, tbl_uo_step.uo_step_descr;"
This is however not very friendly to many changes. So my question is, how do I get the array to send each value as a separate parameter to the query?
Note: IsEmpty() is a custom function which checks for empty variables in case you were wondering.
You can still use a parameterized query in this case, despite your comment to the question. You just need to build the SQL string to include as many parameters as required, something like this:
Dim cdb As DAO.Database, qdf As DAO.QueryDef, rst As DAO.Recordset
Dim sql As String, i As Long
' test data
Dim idArray(1) As Long
idArray(0) = 1
idArray(1) = 3
Set cdb = CurrentDb
sql = "SELECT [LastName] FROM [People] WHERE [ID] IN ("
' add parameters to IN clause
For i = 0 To UBound(idArray)
sql = sql & "[param" & i & "],"
Next
sql = Left(sql, Len(sql) - 1) ' trim trailing comma
sql = sql & ")"
Debug.Print sql ' verify SQL statement
Set qdf = cdb.CreateQueryDef("", sql)
For i = 0 To UBound(idArray)
qdf.Parameters("param" & i).Value = idArray(i)
Next
Set rst = qdf.OpenRecordset(dbOpenSnapshot)
' check results
Do Until rst.EOF
Debug.Print rst!LastName
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Set qdf = Nothing
Set cdb = Nothing
When I run this on my test database I get
SELECT [LastName] FROM [People] WHERE [ID] IN ([param0],[param1])
Thompson
Simpson
you could make use of the IN Clause, instead. Which would work out better.
Do Until i = size + 1
If Not IsEmpty(gvaruocat(i)) Then
If Not IsEmpty(DLookup("uo_cat_id", "tbl_uo_cat", "[uo_cat_id] = " & CInt(gvaruocat(i)))) Then
If IsEmpty(get_uocat_param) Then
get_uocat_param = CInt(gvaruocat(i))
Else
get_uocat_param = get_uocat_param & ", " & CInt(gvaruocat(i))
End If
End If
End If
i = i + 1
Loop
Then your Query build could use,
get_uocat = "SELECT tbl_product.prod_descr, tbl_uo_cat.uo_cat_descr, tbl_uo_step.uo_step_descr" & vbCrLf _
& "FROM (tbl_product INNER JOIN tbl_uo_cat ON tbl_product.prod_id = tbl_uo_cat.uo_cat_prod) INNER JOIN tbl_uo_step ON tbl_uo_cat.uo_cat_id = tbl_uo_step.uo_step_cat" & vbCrLf _
& "WHERE ((tbl_uo_step.uo_step_cat IN (" & get_uocat_param & "))) " & vbCrLf _
& "ORDER BY tbl_product.prod_descr, tbl_uo_cat.uo_cat_descr, tbl_uo_step.uo_step_descr;"
So, the following selects a random team to be used. Once selected, I mark this team being as used as an X in the Used field with a update query later on. For the most it works, but after running this a handful of times, I start to get duplicated teams, even with them being marked as X.
What else am I missing to accomplish this?
Here is the SQL statement:
SELECT TOP 1 RandomTeams.[Team Name], RandomTeams.Used
FROM RandomTeams
WHERE (((RandomTeams.Used) Is Null))
ORDER BY Rnd(TeamID);
Here's how I'm handling the updates to mark a team as being used, which is working as expected, I have no issues here when marking with an X:
Text214.Text contains the team name that is being used
strTeam = (Chr(34) + Text214.Text + (Chr(34)))
strSQLUpdateTeams = "UPDATE RandomTeams SET Used = 'X' WHERE [Team Name] = " & strTeam
DoCmd.SetWarnings (WarningsOff)
DoCmd.RunSQL strSQLUpdateTeams
As a test, how about just throwing the following code into a module, then execute it and see what happens. BTW, how are you resetting [Used]?
Sub Test_Teams()
Dim strSQL As String
Dim strTeam As String
Dim strSQLUpdateTeams As String
Dim dbs As DAO.Database
Dim rs As DAO.recordSet
Set dbs = CurrentDb
If MsgBox("Do you want to reset all 'Used' flags?", vbYesNo, "Reset?") = vbYes Then
strSQL = "update RandomTeams set [Used] = null;"
dbs.Execute strSQL
End If
MyLoop:
strSQL = "SELECT TOP 1 RandomTeams.[Team Name], RandomTeams.Used " & _
"FROM RandomTeams " & _
"WHERE (((RandomTeams.Used) Is Null)) " & _
"ORDER BY Rnd(TeamID);"
Set rs = dbs.OpenRecordset(strSQL)
If Not rs.EOF Then
strTeam = rs![Team Name]
Debug.Print "Found Team: " & strTeam
Else
MsgBox "EOF! No more teams."
rs.Close
Set rs = Nothing
dbs.Close
Set dbs = Nothing
Exit Sub
End If
strTeam = (Chr(34) + rs![Team Name] + (Chr(34)))
rs.Close
Set rs = Nothing
strSQLUpdateTeams = "UPDATE RandomTeams SET [Used] = 'X' WHERE [Team Name] = " & strTeam
Debug.Print strSQLUpdateTeams
'DoCmd.SetWarnings (WarningsOff)
'DoCmd.RunSQL strSQLUpdateTeams
dbs.Execute strSQLUpdateTeams
If dbs.RecordsAffected <> 1 Then
MsgBox "Whoa! Not good! Update failed!"
End If
GoTo MyLoop
End Sub
I am trying to write an if loop for MS Access VBA
In php I would write:
if($query=="0"){
run query 1
} else {
run query 2
}
I do need to call the query in and refer to multiple tables (ie. 'query 1' will extract data from a combo box, whereas, 'query 2' will run another query)
------------------------------------EDIT: 02/06/14 13:34 AEST ----------------------------
Dim variabl1 As String
variabl1 = Me.cmbItemDetails.Column(1)
Dim variabl2 As String
variabl2 = "" & Forms!frmRaiseOrder!cmbDebtorCode & ""
'you can use variable as a parameter in SQL, but only if you hardcode your SQL statement as a string... See directly below
Dim SQL As String
SQL_count = "SELECT COUNT(CustItemPrice) FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
SQL_select = "SELECT CustItemPrice FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset(SQL_count)
If rs.RecordCount = "0" Then
Me.txtStreetPrice.Value = Me.cmbItemDetails.Column(3)
Else
DoCmd.OpenQuery "qrySelectCustomerName"
End If
Thanks to #MurDeR for the assistance for the above statements
----------------------------------------------- Update as of 9th July -----------------------------------
Hi everyone;
If you are trying to create an IF() statement in ACCESS VBA, use the following syntax...
Private Sub cmbItemDetails_Change()
Me.txtItemDescription.Value = Me.cmbItemDetails.Column(2)
Me.txtStreetPrice.Value = Me.cmbItemDetails.Column(3)
Me.txtItemName.Value = Me.cmbItemDetails.Column(1)
Dim variabl1 As String
variabl1 = Me.cmbItemDetails.Column(0)
Dim variabl2 As String
variabl2 = "" & Forms!frmRaiseOrder!cmbDebtorCode & ""
'you can use variable as a parameter in SQL, but only if you hardcode your SQL statement as a string... See directly below
Dim SQL As String
SQL_count = "SELECT COUNT(CustItemPrice) FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
SQL_select = "SELECT CustItemPrice FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
Dim rs As Recordset
Set rs = Nothing
Set rs = CurrentDb.OpenRecordset(SQL_count)
RecordCount = rs.Fields(0)
If RecordCount = "1" Then
'SPECIAL PRICE EXISTS - this code will run only if the count query is greater than zero
MsgBox "Special Price Exists", vbOkay, "Alert"
'
'
Me.txtUnitPrice.Value = Me.cmbItemDetails.Column(3)
'Me.txtUnitPrice.Value = "" & Forms!frmRaiseOrder!subformCreateOrder!frmSelectCustomPriceinsubform!CustItemPrice & ""
'Me.txtUnitPrice.Value = Me.subfrmItemPrice.CustItemPrice.Value
Else
'NO SPECIAL PRICE - this code will run only if the coutn query is zero
'MsgBox "No Special Pricing for this item", vbOkay, "Alert"
'
'
Me.txtUnitPrice.Value = Me.cmbItemDetails.Column(3)
End If
End Sub
I would really like to thank and credit #MurDeR for their help and also if you have any questions, PM me or post here
You can work with a recordset in VBA.
See this bit of code for a start.
Dim variabl As String
variabl = Me.ComboBox1.Value
'you can use variabl as a parameter in SQL, but only if you hardcode your SQL statement as a string... See directly below
Dim SQL As String
SQL = "SELECT * FROM TableA WHERE YourColumnName = '" & variabl & "'"
Dim db As DAO.Database
db = CurrentDb
Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("SQL Statement or Query Name")
If rs.RecordCount = 0 Then
DoCmd.OpenQuery "Query1"
Else
DoCmd.OpenQuery "Query2"
End If
rs.Close
Set rs = Nothing
Let me know if you have any other questions. Also note, you need to make sure you're entering proper query names. I know VBA has pathetic intellisense, so this can be tricky when entering query names as strings.