I'm new to all coding, I'm looking to update a SQL table, using VBA.
There are 4 columns that need to be updated, and then 4 other columns where to put the new data- so they link up to each other for example A and E link. A is where I want the most updated version of the data and E is where you put it in. I have another column where the user will mark an 'x' if they want these columns updated. I've got the beginning all sorted, connecting it to SQL its just the actual update part I'm stuck with...
So where the Upload Indicator is marked with an x then those columns should be updated, if there is no x just leave them as they are.
'SQL update from four check columns from E-H
'Set Value from "Check Column"
'Where UpdateIndicator sht.Cells(Row,15) = "x"
sSQL = "Update [table].[dbo].[]"
Set Check_titles= titles
Set Check_ratings= ratings
Set Check_star= star
Set Check_location= location
Where "Update Indicator" = x
Ive had to change a lot for an example as its confidential, so makes it slightly harder to explain
Sounds like you need to iterate through your cells in excel, and create an update statement for each row. Something like
Dim n As Integer
Dim sql As String
Do Until Cells(n,1) = ""
If Cells(n,5) = "x"
sql = "Update [dbo].[MyTable] SET "
sql = sql + "Check_titles = '" + Cells(n, 2) + "',"
sql = sql + "Check_ratings = '" + Cell(n, 3) + "',"
sql = sql + "Check_star = '" + Cells(n, 4) + "',"
sql = sql + "Check_location = '" + Cells(n, 5) + "'"
sql = sql + " WHERE Id = " + Cells(n,1) 'Assumes unique id in col 1
MyConn.Execute(sql)
End If
Loop
Where MyConn is your MySql connection and n represents the row number and substitute the column numbers for the correct values for the column names.
Related
I am planning to search and update records which matches my criteria in my table through a form.
I want my code to search for OrderNo and OrderNoItem ( For each orderno I have multiple OrderNoItems like 10,20,30... in my table) when there is a match I want to update the customer name(Text18.Value) from my Form.
I have the following code. For some reason it is just updating only the first record. For example when I input Text25.Value = 12345, Text27.Value = 20 and Text49.Value = 40, it is updating the customer name only for the rows with 12345 and 20. Can any one help??
Set logDB1 = CurrentDb()
Set logRS1 = logDB1.OpenRecordset("Log")
For i = Text27.Value To Text49.Value Step 10
Do Until logRS1.EOF
If (logRS1![OrderNo] = Text25.Value And logRS1![OrderNoItem] = Text27.Value) Then
logRS1.Edit
logRS1![DTN-#] = Text18.Value
logRS1.Update
End If
logRS1.MoveNext
Loop
Next
Because code is set to do that. That's exactly what the If condition requires. What you should do is open the recordset filtered by OrderNo and the OrderNoItem range then just loop those records.
Set logDB1 = CurrentDb()
Set logRS1 = logDB1.OpenRecordset("SELECT [DTN-#] FROM Log WHERE OrderNo='" & _
Me.Text25 & "' AND Val(OrderNoItem) BETWEEN " & Me.Text27 & " AND " & Me.Text49)
Do Until logRS1.EOF
logRS1.Edit
logRS1![DTN-#] = Me.Text18
logRS1.Update
logRS1.MoveNext
Loop
Or instead of opening and looping recordset, Execute an UPDATE action SQL:
CurrentDb.Execute "UPDATE Log SET [DTN-#]='" & Me.Text18 & _
"' WHERE OrderNo = '" & Me.Text25 & "' AND Val(OrderNoItem) BETWEEN " & Me.Text27 & " AND " & Me.Text49
If OrderNo is a number field, remove the apostrophe delimiters.
Strongly advise not to use punctuation/special characters (underscore is only exception) in naming convention. Better would be DTN_Num.
I have two txt boxes and two combo boxes on a form. There is also a subform linked to the temptable that I want to have rebuilt/filter each time one of the controls is changed (using after update on each control to trigger the following sub)
I receive Run-time error '91: Object variable or with block variable not set on line Items(i) = Thing
I am not sure using " (i) " works with MS Access 365 or I am dimensioning incorrectly?
Thank you.
Private Sub Lookupstuff()
Dim i As Integer
Dim Items(1 To 4) As Object
sql = "DELETE * FROM tblTemp"
CurrentDb.Execute sql
i = 0
FilterArray = Array(Me.txtNew, Me.cmbS, Me.cmbP, Me.txtSl)
For Each Thing In FilterArray
If Not IsNull(Thing) Then
i = i + 1
Items(i) = Thing <--Error is here. Items(i) is empty.
End If
Next
If i = 0 Then
Forms!frmNew.Requery
Forms!frmNew.Refresh
End If
If i = 1 Then
Filter = Items1
End If
If i = 2 Then
Filter = Items1 & " AND " & Items2
End If
If i = 3 Then
Filter = Items1 & " AND " & Items2 & " AND " & Items3
End If
If i = 4 Then
Filter = Items1 & " AND " & Items2 & " AND " & Items3 & " AND " & Items4
End If
sql = "INSERT INTO tblTemp SELECT * FROM tblQ"
If Not IsNull(Filter) Then
sql = sql & " WHERE " & Filter
End If
CurrentDb.Execute sql
Forms!frmNew.Requery
Forms!frmNew.Refresh
End Sub
Since you are assigning a reference to object in the array, you must use Set, i.e.:
Set Items(i) = Thing
Also, presumably each reference to Items1, Items2 etc. should actually be Items(1), Items(2) in order to access the objects referenced at these indices of the array.
I have a sub that is supposed to take a number of assignments (this number changes daily) and assign them to 7 associates. There are some conditions to this:
If the # of assignment is less than 7, it assigns all of them to a random associate.
If the # is divisible by 7, it assigns an equal number to each.
If it is not divisible by 7, it assigns equally and then gives the remainder to a random associate.
The problem is the random part. I really don't understand how random works in vba, or at least it seems like it should be super easy, but it's not (maybe). But I have this written and it's not working. (Associates(Int(Rnd() * 7) + 1)). Here is my relevant code:
Earlier in the sub I create an array of the associates and I use some dcounts to get the total assignments for that day:
Dim Associates(6) As Integer
Associates(0) = 4687 'Anita
Associates(1) = 4247 'Alberto
Associates(2) = 2167 'Jeff
Associates(3) = 4334 'Lisa
Associates(4) = 4441 'Carrie
Associates(5) = 2052 'Bobby
Associates(6) = 4657 'Simona
'
Dim Person As Variant
'
TotalPop = DCount("LNo", "qry_PT_Assign")
FractionPop = Int(TotalPop / 7)
LeftPop = TotalPop - (FractionPop * 7)
'
and then I try to actually assign them.
'Assign to Associates
If TotalPop < 7 Then
DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & (Associates(Int(Rnd() * 7) + 1)) & " WHERE AudTellerID IS NULL"
ElseIf LeftPop = 0 Then
For Each Person In Associates
DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & Person & " WHERE LNo IN (SELECT TOP " & FractionPop & " LNo FROM tbl_Assignments WHERE AudTellerID Is Null)"
Next
Else
For Each Person In Associates
DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & Person & " WHERE LNo IN (SELECT TOP " & FractionPop & " LNo FROM tbl_Assignments WHERE AudTellerID Is Null)"
Next
DoCmd.RunSQL "UPDATE tbl_Assignments SET AudTellerID = " & (Associates(Int(Rnd() * 7) + 1)) & " WHERE AudTellerID IS NULL"
End If
As per my comment, try generating the random number first, assign it to a variable, and then pass the variable into Associates().
Dim rndInt as Integer
rndInt = Int(Rnd() * 7) + 1
Associates(rndInt)
Then as #Chips said, you can use
Debug.print rndInt
Or
Msgbox rndInt
to check its value
That way you'll be able to see what number is actually being generated
The trick is to use a negative seed that changes constantly.
So add a time dependant seed to Rnd which changes for every unique id like in this sample select query:
SELECT
Table1.ID,
Table1.SomeField,
Table1.AnotherField,
Rnd(-Timer()*[ID]) AS RandomIndex
FROM
Table1
ORDER BY
Rnd(-Timer()*[ID]);
In your code, the expression could be something like this:
.. " & (Associates(Int(Rnd(-Timer()*" & [ID] & ") * 7) + 1)) & " ..
I have syntax error in this code
string JSS_connetionString011 = null;
OleDbConnection JSS_connection011;
OleDbDataAdapter JSS_oledbAdapter011 = new OleDbDataAdapter();
string JSS_sql011 = null;
JSS_connetionString011 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/je_salestoredb.mdb;Persist Security Info=True;Jet OLEDB:Database Password=JEPTUSJSSJes";
JSS_connection011 = new OleDbConnection(JSS_connetionString011);
JSS_sql011 = "update product set Siv_Sales_Invoice_NO = '" + textBox1.Text + "' , prod_Status = '" + JSS_product_Status + "' , prod_SALED_ftrCalc = '" + textBox10.Text + "' , piv_SALED_DATE = '" + dateTimePicker1.Text + "' , sivd_ID = '" + textBox3.Text + "' , prod_ROOM ='" + JSS_product_Warhousee + "' where( prod_COMPANY = '" + comboBox4.Text + "' and prod_MODEL = '" + comboBox5.Text + "' and prod_Status = '" + JSS_Ready_For_Sale + "' ORDER BY prod_COMPANY LIMIT 1 )";
JSS_connection011.Open();
JSS_oledbAdapter011.UpdateCommand = JSS_connection011.CreateCommand();
JSS_oledbAdapter011.UpdateCommand.CommandText = JSS_sql011;
JSS_oledbAdapter011.UpdateCommand.ExecuteNonQuery();
Syntax error (missing operator) in query expression '( prod_COMPANY = 'NSN' and prod_MODEL = '606' and prod_Status = 'true' ORDER BY prod_COMPANY LIMIT 1 )'.
There are many records with the same conditions of the query sentence, but each of them have different id.
Any Ideas?
Okay, a couple of things:
One, you can't use ORDER BY or LIMIT in an UPDATE statement in an Access database. The example you linked to is for MySQL, a different database.
Two: What Jon Skeet says is absolutely true: you need to use parameterized SQL rather than putting values directly in SQL.
Three: Given that ORDER BY and LIMIT are not valid in Access update statements, if you replace this bit of code:
+ JSS_Ready_For_Sale + "' ORDER BY prod_COMPANY LIMIT 1 )";
... with this:
+ JSS_Ready_For_Sale + "')";
... the syntax error, or at least that syntax error, may go away.
You might also want to be put a space between the WHERE and the (. I don't know that that will count as a syntax error, but it might.
ETA: ALSO! If you only want to update one record, the one with a specific ID (which I infer from your question text) you will need to specify that record ID in the WHERE clause.
If you records don't have unique IDs, you have a very big problem that you need to fix. A unique ID is absolutely required if you want to be able to update a specific record.
You will also need a properly format string expression for the date:
piv_SALED_DATE = #" + dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "# ,
and in Access SQL you will use "Select Top n .." to select the first n values.
I have retrieve all data from the internet into a 2 dimension array, I know how to use vba recordset and by filter and update using loop. Below is part of the code in vba.
the difficult problem is here:
Using cmd As New MySqlCommand("INSERT INTO `calls` (`CID`, `ctype`) VALUES (#CID, #ctype)", cnn)
This make me could not use any loop through the array and update accordingly.
cmd.Parameters.Add ('#CID').value = arrValue(i,j)
I hope this could be done in kind of below:
for x = 0 to ubound(arrValue,0)
for y = 0 to ubound(arrValue,1)
.fields(arrHeader(y) = arrValue(x,y)
next y
next x
say i, the n-th to be updated, j = the value of the header
extract of vba:
With rs
'Worksheets(strWsName).Activate
'iLastRow = Worksheets(strWsName).Cells(65535, 1).End(xlUp).row 'column B, column 2
For i = 0 To UBound(arrValue, 1)
Debug.Print "Updating " & i + 1 & " of " & UBound(arrValue, 1) + 1 & " news ..." ' of " & strCodeAB & " ..."
'Start looping the news row
strNewsID = arrValue(i, 1) 'Worksheets(strWsName).Range(ColRefNewsID & i).Value
If strNewsID = "" Then
Debug.Print i - 1 & " news is updated to database"
i = UBound(arrValue, 1)
Else
strFilter = "fID='" & strNewsID & "'"
rs.Filter = strFilter
If rs.EOF Then
.AddNew 'create a new record
'add values to each field in the record
For j = 0 To UBound(arrTitle_ALL)
'20140814
strFieldValue = .Fields(arrAccessField(j))
strNewValue = arrValue(i, j)
If IsNull(strFieldValue) And strNewValue = "" Then
Else
.Fields(arrAccessField(j)) = arrValue(i, j) 'Worksheets(strWsName).Cells(i, j + 1).Value
End If
Next j
On Error Resume Next '***************
.Update 'stores the new record
On Error GoTo 0
iCounterNewsAdded = iCounterNewsAdded + 1
glcounterNewsAdded = iCounterNewsAdded
Else
It seems that the below post similar to my request but I don't know how to do so.
[reference]passing an Array as a Parameter to be used in a SQL Query using the "IN" Command
The post you mention (Using the IN() command) works in your WHERE clause but it is not valid for values. MySQL has no way to pass an array so you need to loop through your array and run multiple INSERT statements:
for y = 0 to ubound(arrValue,1)
cmd.Parameters.AddWithValue(#CID,arrValue(0,y))
cmd.Parameters.AddWithValue(#ctype,arrValue(1,y))
cmd.ExecuteNonQuery
next y