I have created a table where I'm saving attachments(in external folder) and file paths in the table. When I'm trying to update existing attachment with another, it does not work. Please see below "Add file" code and "Update button" code.
Private Sub cmAdd_Click()
On Error Resume Next
Dim strLokacioni As String
Dim strSQL As String
strLokacioni = "C:\Users\HSE\Desktop\datas\" & getFileName(Me.path.Value)
strSQL = "INSERT INTO tbl_tracker(path, filename, IncNo, PATS, SAP, First, Last, IncDate, Description, Location, OshaType, IncType, RootCause,Inspector, Surfaces, WeatherCon, WorkRelated, IncTime)" & _
"VALUES ( '" & strLokacioni & "', '" & Me.path.Value & "', '" & Me.txtInc & "', '" & Me.txtPATS & "', '" & Me.txtSAP & "', '" & Me.txtFirst & "', '" & Me.txtLast & "', '" & Me.txtDate & "', '" & Me.txtDesc & "', '" & Me.cmbLoc & "', '" & Me.cmbOsha & "', '" & Me.cmbType & "', '" & Me.txtCause & "', '" & Me.cmbInsp & "', '" & Me.cmbSur & "', '" & Me.cmbWcon & "', '" & Me.cmbRelated & "', '" & Me.txtTime & "')"
CurrentDb.Execute (strSQL)
MsgBox "Record Added", vbInformation, "Information"
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
fso.CopyFile Me.path.Value, strLokacioni
Set fso = Nothing
Me.tbl_tracker_subform.Form.Requery
End Sub
' Below is update button code
Private Sub Command88_Click()
'On Error Resume Next
Dim strLokacioni As String: strLokacioni = "C:\Users\HSE\Desktop\datas\" & getFileName(Me.path.Value)
Me.path = strLokacioni
CurrentDb.Execute "UPDATE tbl_tracker " & _
" SET IncNo = " & Me.txtInc & _
", path = '" & strLokacioni & "'" & _
", filename = '" & Me.filename & "'" & _
", PATS = '" & Me.txtPATS & "'" & _
", SAP = '" & Me.txtSAP & "'" & _
", First = '" & Me.txtFirst & "'" & _
", Last = '" & Me.txtLast & "'" & _
", IncDate = '" & Me.txtDate & "'" & _
", Location = '" & Me.cmbLoc & "'" & _
", Description = '" & Me.txtDesc & "'" & _
", OshaType = '" & Me.cmbOsha & "'" & _
", Inctype = '" & Me.cmbType & "'" & _
", RootCause = '" & Me.txtCause & "'" & _
", Inspector = '" & Me.cmbInsp & "'" & _
", Surfaces = '" & Me.cmbSur & "'" & _
", WeatherCon = '" & Me.cmbWcon & "'" & _
", WorkRelated = '" & Me.cmbRelated & "'" & _
", IncTime = '" & Me.txtTime & "'" & _
" WHERE IncNo = " & Me.txtInc.Tag
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
fso.CopyFile Me.path.Value, strLokacioni
Set fso = Nothing
MsgBox "Record Updated", vbInformation, "Information"
Me.tbl_tracker_subform.Form.Requery
End sub
And the the value Me.path.Value at the start of Command88_click is coming from :
Public Function getFileName(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
getFileName = getFileName(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
Private Sub cbdBrowse_Click()
On Error Resume Next
Dim f As Object
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.AllowMultiSelect = False
f.Show
Me.path.Value = f.SelectedItems(1)
End Sub
When I use update queries like you have here, I would always use the following syntax.
dim db as database
set db = currentDb
db.execute "UPDATE...."
would you require the same? Or have I been going about this a long way.
Also, I would have left a comment as this may not be the answer. Unfortunately, I cant due to rep<50
Related
I have a button that lets me select a file to choose, that location of the file gets saved to a textbox, I use the location from the textbox to upload a file to a data base and I get an error.
"An INSERT INTO query cannot contain a multi-valued field."
Following is my code.
Private Sub btn_Browse_Click()
Dim f As Object
Dim strFile As String
Dim strFolder As String
Dim varItem As Variant
Set f = Application.FileDialog(3)
f.allowMultiSelect = True
If f.Show Then
For Each varItem In f.selectedItems
strFile = Dir(varItem)
strFolder = Left(varItem, Len(varItem) - Len(strFile))
MsgBox "Folder: " & strFolder & vbCrLf & _
"File: " & strFile
Me.txt_PicSource = strFolder + strFile
Next
End If
Set f = Nothing
...
CurrentDb.Execute _
"INSERT INTO Field_Return_Table(Date_FRL, Time_FRL, Client_FRL, Product_FRL, LOT_FRL, Territory_FRL, Tracking_FRL, Condition_FRL, Location_FRL, Completed_By_FRL, Comments_FRL, Attachment_FRL) " & _
"VALUES ('" & strDate & "', '" & strDate & "', '" & Me.combo_Client.Value & "', '" & Me.txt_Product.Value & "', '" & Me.txt_Lot.Value & "', '" & Me.txt_Territory.Value & "', '" & Me.txt_Track.Value & "', '" & strCondition & "', '" & strLocation & "', '" & strUser & "', '" & Me.txt_Comment.Value & "', '" & Me.txt_PicSource.Value & "')"
...
Any tips of how to upload this file via the INSERT INTO?
I have 3 combobox to filter data, then i want to open in command button to print preview..
Problems I have if i used 2 combobox it works but when i used three combobox the report is blank...there's any problems with the code?? here's the code i used :
Dim strWhereCondition As String
strWhereCondition = "[month] = '" & Me.cbmonth.Value _
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Debug.Print strWhereCondition
DoCmd.OpenReport "Month List", View:=acViewPreview, _
WhereCondition:=strWhereCondition
and the requery for my form
SELECT *
FROM MyTable
WHERE (month = Forms!nameForm!cbmonth
OR Forms!MeForm!cbwork IS NULL)
And (works = Forms!nameForm!cbwork
OR Forms!nameForm!cbwork IS NULL)
AND (works = Forms!nameForm!cbwork2
OR Forms!nameForm!cbwork2 IS NULL);
can anyone help?
Month is a number, so try:
strWhereCondition = "[month] = " & Me.cbmonth.Value _
& " and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Edit: Month is text.
However, [Work] is supposed to match two potentially different values:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Should most likely be:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [SomeOtherField] = '" & Me.cbwork2.Value & "'"
How I can prevent duplicate values to not insert into the table. I have created a code to INSERT, UPDATE and DELETE and I want to display a MsgBox that there is a duplicate value and to cancel it. Thanks. Below you have the code:
Private Sub Command12_Click()
If Me.emID.Tag & "" = "" Then
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
CurrentDb.Execute "INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment)" & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "')"
MsgBox "Record Added", vbInformation, "information"
Else
CurrentDb.Execute "UPDATE tblEmployees " & _
"SET emiD =" & Me.emID & _
", first ='" & Me.emFirst & "'" & _
", last = '" & Me.emLast & "'" & _
", gender ='" & Me.emGender & "'" & _
", phone = '" & Me.emPhone & "'" & _
", mobphone ='" & Me.emMob & "'" & _
", city ='" & Me.emCity & "'" & _
", state ='" & Me.emState & "'" & _
", zip ='" & Me.emZip & "'" & _
", adress ='" & Me.emAdress & "'" & _
", email ='" & Me.emEmail & "'" & _
", comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
It sounds like you'd like to update an employee if one exists for the given ID otherwise you'd like to add a new employee. You can prevent adding duplicate employees by first trying to update an employee record with the given ID and if no records were updated only then do you add a new employee record.
Private Sub Command12_Click()
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
' You must set CurrentDb to a variable otherwise the RecordsAffected
' property used later will be incorrect.
Dim db As DAO.Database
Set db = CurrentDb
' First try to update an existing employee.
db.Execute _
"UPDATE tblEmployees " & _
"SET first ='" & Me.emFirst & "', " & _
"last = '" & Me.emLast & "', " & _
"gender ='" & Me.emGender & "', " & _
"phone = '" & Me.emPhone & "', " & _
"mobphone ='" & Me.emMob & "', " & _
"city ='" & Me.emCity & "', " & _
"state ='" & Me.emState & "', " & _
"zip ='" & Me.emZip & "', " & _
"adress ='" & Me.emAdress & "', " & _
"email ='" & Me.emEmail & "', " & _
"comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag & ";"
' If no records were affected by update then add a new employee.
If db.RecordsAffected = 0 Then
db.Execute _
"INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment) " & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "');"
MsgBox "Record Added", vbInformation, "Information"
Else
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
Note: In the update query I removed the update to the emID field since that is what the query is based on (in the WHERE clause). If the emID field is changing you won't be able to use the new emID value to find an employee record with the old emID value.
If you never want any duplicates I would also suggest that you add constraints to your database table to prevent duplicates, as suggested by Daniel Cook. I would also suggest looking into using parameterized queries instead of building SQL strings in VBA.
You can change your SQL to use IF EXISTS condition and insert only if the records does not already exists.
Your SQL may look like:
IF NOT EXISTS
(
SELECT ......
)
BEGIN
INSERT INTO tblEmployees ......<insert since employee does not exists>
END
I have a form where an admin can add a company to a database table called 'Company'
In this form there is a Drop Down list to select whether a company is a Scholarship Company, there are two options 'Yes' and 'No'. I have created a table to pull these options from called 'YesNo'.
When I select Yes in the drop down list and hit submit it updates the table so the cell for ScholarshipCompany is '1' and not 'Yes'. This works fine in the edit form I have which just updates the company though I am having trouble with the add company form which inserts a new entry into the table.
Please see code below;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("Name") = Nothing Then
Response.Redirect("Login.aspx")
End If
Session("Name") = Session("Name")
Session("Username") = Session("Username")
Try
If Not IsPostBack Then
Dim locationList As OleDbDataReader = Database.DoSQLReturnDataReader("SELECT [{Location}].ID, [{Location}].Location FROM [{Location}] ORDER BY [{Location}].ID")
ddlLocation.DataSource = locationList
ddlLocation.DataTextField = "Location"
ddlLocation.DataValueField = "ID"
ddlLocation.DataBind()
locationList.close()
Dim statusList As OleDbDataReader = Database.DoSQLReturnDataReader("SELECT * FROM EmployerStatus ORDER BY ID ASC")
ddlStatus.DataSource = statusList
ddlStatus.DataTextField = "Status"
ddlStatus.DataValueField = "ID"
ddlStatus.DataBind()
statusList.close()
Dim yesnoList As OleDbDataReader = Database.DoSQLReturnDataReader("SELECT * FROM YesNo ORDER BY ID DESC")
ddlYesno.DataSource = yesnoList
ddlYesno.DataTextField = "Option"
ddlYesno.DataValueField = "Option"
ddlYesno.DataBind()
yesnoList.close()
End If
Catch ex As Exception
Response.Redirect("index.aspx?Yr=" & Replace(Request.QueryString("Yr"), "'", "''"))
End Try
End Sub
Protected Sub BtnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
Dim strSql As String = "INSERT INTO Company(" & _
"CompanyName, " & _
"URL, " & _
"Location, " & _
"EmployerStatus, " & _
"Address, " & _
"ScholarshipCompany, " & _
"ScholarshipNotes, " & _
"Town, " & _
"County, " & _
"Blurb, " & _
"InterviewTips, " & _
"HRContactForename, " & _
"HRContactSurname, " & _
"HREmail, " & _
"Telephone, " & _
"[Password], " & _
"Fax, " & _
"HRContactForename2, " & _
"HRContactSurname2, " & _
"HREmail2, " & _
"Telephone2, " & _
"HRContactForename3, " & _
"HRContactSurname3, " & _
"HREmail3, " & _
"Telephone3, " & _
"Postcode) " & _
"VALUES " & _
"( " & _
"'" & TxtBoxCompanyName.Text.Replace("'", "''") & "', " & _
"'" & TxtBoxURL.Text.Replace("'", "''") & "', " & _
"'" & Replace((ddlLocation.SelectedIndex + 1), "'", "''") & "', " & _
"'" & Replace((ddlStatus.SelectedIndex + 1), "'", "''") & "', " & _
"'" & TxtAreaAddress.InnerText.Replace("'", "''") & "', " & _
"'" & Replace((ddlYesno.SelectedIndex), "'", "''") & "', " & _
"'" & TxtBoxSchol.Text.Replace("'", "''") & "', " & _
"'" & TxtBoxTown.Text.Replace("'", "''") & "', " & _
"'" & TxtBoxCounty.Text.Replace("'", "''") & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & "" & "', " & _
"'" & TxtBoxPostcode.Text.Replace("'", "''") & "'" & _
")"
Dim updateCompanyDetails As OleDbDataReader = Database.DoSQLReturnDataReader(strSql)
updateCompanyDetails.Close()
System.Threading.Thread.Sleep("1000")
Instead of
Replace((ddlLocation.SelectedIndex + 1), "'", "''") & "', " & _
"'" & Replace((ddlStatus.SelectedIndex + 1), "'", "''") & "', " & _
try
Replace((ddlLocation.SelectedValue + 1), "'", "''") & "', " & _
"'" & Replace((ddlStatus.SelectedValue + 1), "'", "''") & "', " & _
or SelectedText
If Me.dcBox & "" = "" Then
CurrentDb.Execute "UPDATE worklogData " & _
" SET [Submitter] = '" & Me.subBox & "'" & _
", [Section] = '" & Me.secBox & "'" & _
", [Received By] = '" & Me.rbBox & "'" & _
", [Date Received] = """ & _
", [Serial Number] = '" & Me.snBox & "'" & _
", [Problem] = '" & Me.probBox & "'" & _
", [Computer Name] = '" & Me.cnBox & "'" & _
", [MAC] = '" & Me.macBox & "'" & _
", [Solution] = '" & Me.solBox & "'" & _
", [Completed By] = '" & Me.cbBox & "'" & _
", [Date Completed] = """ & _
" WHERE [Order] = " & Me.orderBox.Tag & ""
Else
CurrentDb.Execute "UPDATE worklogData " & _
" SET [Submitter] = '" & Me.subBox & "'" & _
", [Section] = '" & Me.secBox & "'" & _
", [Received By] = '" & Me.rbBox & "'" & _
", [Date Received] = #" & Me.drBox & "#" & _
", [Serial Number] = '" & Me.snBox & "'" & _
", [Problem] = '" & Me.probBox & "'" & _
", [Computer Name] = '" & Me.cnBox & "'" & _
", [MAC] = '" & Me.macBox & "'" & _
", [Solution] = '" & Me.solBox & "'" & _
", [Completed By] = '" & Me.cbBox & "'" & _
", [Date Completed] = #" & Me.dcBox & "#" & _
" WHERE [Order] = " & Me.orderBox.Tag & ""
End If
I'm trying to UPDATE my table in Access VBA, but I found it causes Runtime Error: 3075 'Syntax error in date in query expression '#' when I try to UPDATE [Date Completed] field from what was blank previously.
And I've set Me.probBox as some text value which was previously blank, but [Problem] field doesn't be updated. What is surprising is there is no error coming out for this one.
Try this
CurrentDb.Execute "UPDATE worklogData " & _
" SET [Submitter] = '" & Me.subBox & "'" & _
", [Section] = '" & Me.secBox & "'" & _
", [Received By] = '" & Me.rbBox & "'" & _
", [Date Received] = """"" & _
", [Serial Number] = '" & Me.snBox & "'" & _
", [Problem] = '" & Me.probBox & "'" & _
", [Computer Name] = '" & Me.cnBox & "'" & _
", [MAC] = '" & Me.macBox & "'" & _
", [Solution] = '" & Me.solBox & "'" & _
", [Completed By] = '" & Me.cbBox & "'" & _
", [Date Completed] = """"" & _
" WHERE [Order] = " & Me.orderBox.Tag & ""