I want to insert Employee Id but every time the Window appears.
Enter Parameter Value Ad001
Ad001 is the value of me.mstrEMpID.
This is my procedure:
Dim db
Dim tmpempid As String
tmpempid = (Me.mstrEmpID)
sqlqry1 = "INSERT INTO Timesheet ([StrEMPId]) VALUES ( TmpEmpId );"
DoCmd.OpenTable "Timesheet"
DoCmd.SetWarnings False
DoCmd.RunSQL sqlqry1
DoCmd.SetWarnings True
Do you know what is going wrong?
You need to either use string concatenation and delimiters, like this:
Dim tmpempid As String
tmpempid = (Me.mstrEmpID)
sqlqry1 = "INSERT INTO Timesheet ([StrEMPId]) VALUES ( '" & tmpempid & "');"
DoCmd.SetWarnings False
DoCmd.RunSQL sqlqry1
DoCmd.SetWarnings True
Or do it properly, and use parameters:
With CurrentDb.CreateQueryDef("", "INSERT INTO Timesheet ([StrEMPId]) VALUES (?);")
.Parameters(0) = Me.mstrEmpID
.Execute
End With
You need to concatenate the value to create the SQL command:
sqlqry1 = "INSERT INTO Timesheet ([StrEMPId]) VALUES (" & TmpEmpId & ");"
For two parameters:
sqlqry1 = "INSERT INTO Timesheet ([StrEMPId], [Ad002]) VALUES (" & TmpEmpId & ", " & ValueForAd002 & ");"
Related
I am working on a custom VBA script that dynamically collects user-entered form data and inserts it into a MySQL database. My problem is, to convert form field data into an SQL script, I have to use string functions; thus, all my data, including dates, gets inserted as text. I need to convert all the dates the form collects from m/d/yyyy format to yyyy-mm-dd format for my MySQL database to infer schema and load date data into DB without an error. I need to do so dynamically, meaning, the script has to work regardless of how many date fields are collected. I have:
Private Sub Submit_Button()
Dim doc as Document
Dim control As ContentControl
Dim FormDateField As Date
Dim ReportNumber As String
Dim myValues As String
Dim myFields As String
Dim conn As ADODB.Connection
Dim strSQL As String
Set doc = Application.ActiveDocument
Set conn = New ADODB.Connection
conn.open "DSN=ABCD"
For Each control In doc.ContentControls
Skip = False
If Left(control.Range.Text, 5) = "Click" Or Left(control.Range.Text, 6) = "Choose" Then
Skip = True
Else:
myFields = myFields & control.Tag
myValues = myValues & "'" & control.Range.Text & "'"
End If
If Not Skip Then
myFields = myFields & ", "
myValues = myValues & ", "
End If
Next
myFields = Left(myFields, Len(myFields) - 2)
myValues = Left(myValues, Len(myValues) - 2)
strSQL = "INSERT INTO TABLE_1 ("
strSQL = strSQL & myFields
strSQL = strSQL & ") VALUES (" & myValues
strSQL = strSQL & ")"
conn.Execute strSQL
MsgBox "Form data saved to database!"
conn.Close
End Sub
However, my program is crashing because it is trying to insert a string into the date field (the actual final form will have many date fields.) I thought if I change the date format to MySQL format, it may be able to infer schema? I tried adding
If IsDate(control.Range.Text) Then
control.Range.Text = Format(control.Range.Text, "yyyy-mm-dd")
Else FoundOne = False
End If
and I know in Excel you can do:
Application.FindFormat.NumberFormat = "m/d/yyyy"
Application.ReplaceFormat = "yyyy-mm-dd"
Any suggestions? Thank you.
Assuming all dates are in date-picker content controls, you could use:
Private Sub Submit_Button()
Dim CCtrl As ContentControl, bSv As Boolean, DtFmt As String
Dim myFields As String, myValues As String, strSQL As String
With ActiveDocument
bSv = .Saved
For Each CCtrl In .ContentControls
With CCtrl
If .ShowingPlaceholderText = False Then
Select Case .Type
Case wdContentControlDate
DtFmt = .DateDisplayFormat
.DateDisplayFormat = "YYYY-MM-DD"
myFields = myFields & .Tag & ", "
myValues = myValues & "'" & .Range.Text & "', "
.DateDisplayFormat = DtFmt
Case wdContentControlRichText, wdContentControlText, wdContentControlDropdownList, wdContentControlComboBox
myFields = myFields & .Tag & ", "
myValues = myValues & "'" & .Range.Text & "', "
Case Else
End Select
End If
End With
Next
.Saved = bSv
End With
If myFields <> "" Then
myFields = Left(myFields, Len(myFields) - 2)
myValues = Left(myValues, Len(myValues) - 2)
strSQL = "INSERT INTO TABLE_1 (" & myFields & ") VALUES (" & myValues & ")"
Dim Conn As New ADODB.Connection
With Conn
.Open "DSN=ABCD": .Execute strSQL: .Close
End With
Set Conn = Nothing
MsgBox "Form data saved to database", vbInformation
Else
MsgBox "No form data found", vbExclamation
End If
End Sub
As you noticed, Word does not have Application.FindFormat or Application.ReplaceFormat, but if you know the format is m/d/y you should be able to do this:
myValues = myValues & "'" & ymd(control.Range.Text) & "'"
Function ymd(s as String) As String
Dim v As Variant
v = VBA.split(s, "/")
ymd = Right("0000" & v(2),4) & "-" & Right("00" & v(0),2) & "-" & Right("00" & v(1),2)
End Function
Everything else (e.g. the way you add commas to the list of dates) looks fine but I have not tested.
I'm passing record set from one function (i.e.chkMismatchData) to another (CheckMismatches) and if the record is not found I update some values of passed recordset.
Even I declare variable of recordset in module level still finding the error.
My code is :
Set rec1 = CurrentDb.OpenRecordset("select * from CBWCFAVENDORMATCHOFFMASTER where [vendor]='" & rec![Vendor] & "'")
While Not rec.EOF
Set rec3 = CurrentDb.OpenRecordset("select ID,[HCI_NO],CLEARLOC,SUM([AMOUNT])AS AMOUNT1 from CBWCFAMISUPLOAD WHERE [vendor]='" & rec![Vendor] & "' and nz([match],'')='' and nz([HCI_NO],'')<>'' GROUP BY HCI_NO,CLEARLOC,ID ")
While Not rec3.EOF
Set rec2 = CurrentDb.OpenRecordset("select ID,DEPSLIPNO,CLEARLOC from CBWCFAPENDINGPAYMENTDATA WHERE [DEPSLIPNO]='" & rec3![HCI_NO] & "' GROUP BY DEPSLIPNO,CLEARLOC,ID HAVING CLEARLOC='" & rec3![CLEARLOC] & "' AND SUM([amt])=" & rec3![AMOUNT1])
If rec2.EOF = False Then
If rec2.RecordCount = 1 Then
CurrentDb.Execute ("UPDATE CBWCFAMISUPLOAD SET [MATCH]='Y' ,[CASHIN_ID]='" & rec2![ID] & "' WHERE [HCI_NO]='" & rec3![HCI_NO] & "' ")
CurrentDb.Execute ("UPDATE CBWCFAPENDINGPAYMENTDATA SET [MATCH]='Y' ,[MIS_ID]='" & rec3![ID] & "' WHERE [DEPSLIPNO]='" & rec3![HCI_NO] & "'")
ElseIf rec1.RecordCount > 1 Then
Call UpdateRec(rec3, 0, "Duplicate Match", 0)
End If
Else
strSlipType = "HCI_NO"
Call UpdateRec(rec3, 0, CheckMismatches(rec3), 0) 'here im passing
End If
rec3.MoveNext
Wend
Wend
Private Function CheckMismatches(rec As DAO.Recordset) As String
Dim RecCheck As DAO.Recordset
Dim strDepSlipNo As String, strID As String
If strSlipType = "HCI_NO" Then
'--Clearing Loc Not Matching
Set RecCheck = CurrentDb.OpenRecordset("select ID,DEPSLIPNO,CLEARLOC from CBWCFAPENDINGPAYMENTDATA WHERE [DEPSLIPNO]='" & rec![HCI_NO] & "' GROUP BY DEPSLIPNO,CLEARLOC,ID HAVING CLEARLOC<>'" & rec![CLEARLOC] & "' AND SUM([amt])=" & rec![AMOUNT1])
If RecCheck.EOF = True Then
rec.Edit 'here i'm geting error
rec![match]="Y" 'added line
rec!.update 'added line
CheckMismatches = "Clearing Loc Not Matching"
RecCheck.Close
Exit Function
End If
RecCheck.Close
end function
Your rec3 has a GROUP BY clause.
A recordset that is aggregated is by definition read-only. So you have to edit the table separately from this recordset.
Why do you have rec.Edit in the function when you don't edit any fields of it?
In an event of a Form I write some code to select value from a table and insert it into another table. This is my code:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT std_crs_absence.std_name, std_crs_absence.stg_number, std_crs_absence.crs_name, Sum(std_crs_absence.absence_time) AS SumOfabsence_time, Sum(std_crs_absence.molat) AS SumOfmolat " & _
"FROM std_crs_absence GROUP BY std_crs_absence.std_name, std_crs_absence.stg_number, std_crs_absence.crs_name ", dbOpenDynaset)
rs.MoveFirst
Do Until rs.EOF
sqlinsert = "INSERT INTO abs_summary ([std_name],[stg_number],[crs_name],[SumOfabsence_time],[SumOfmolat])" & _
" VALUES ('" & rs("std_name") & "','" & rs("stg_number") & "','" & rs("crs_name") & "'," & rs("absence_time") & "," & rs("molat") & ")"
DoCmd.RunSQL (sqlinsert)
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
When the event is executed it gives me an error that says "Item not found in this collection". What am I doing wrong?
When you first SELECT the data you retrieve the sums as SumOfabsence_time and SumOfmolat, but for the INSERT you try to use rs("absence_time") and rs("molat"). Those columns don't exist in the Recordset so you get the error. You'll need to use rs("SumOfabsence_time") and rs("SumOfmolat") instead.
(Obligatory comment: You really should be using a parameterized query instead of dynamic SQL.)
I am trying to loop through a series of comboboxes on my form, skip the blanks and then added them to a database, but it seems to be failing - any idea how I can do this?
For i = 1 To 8
If Not (("cboOption" & i).Value = "") Then
StrSQL = "INSERT INTO db (mID, uID) VALUES (("cboOption" & i).Value = "", StudentID.Value);"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
End If
Next
Well I am not 100% sure, but the code you have might throw a method or data not recogonised error. Anyway, the following code should sort it.
For i = 1 To 8
If Len(Me.Controls("cboOption" & i).Value & vbNullString) <> 0 Then
StrSQL = "INSERT INTO db (mID, uID) VALUES (" & _
Me.Controls("cboOption" & i).Value & ", " & _
StudentID.Value & ");"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
End If
Next
Just make sure to wrap the values inside single quotes if they are string values.
StrSQL = "INSERT INTO db (mID, uID) VALUES ('" & _
Me.Controls("cboOption" & i).Value & "', " & _
StudentID.Value & ");"
I am trying to create a change log anytime a field is changed. I want it to record the property, the manager, and the date it was changed. I looked up INSERT INTO and followed the directions and came up with this code, but I get an error.
Private Sub Manager_AfterUpdate()
INSERT INTO tbl_ManagerChangeLog (Property, NewMan, [Date Change])
VALUES (Me.ID, Me.Manager, DATE())
End Sub
There error I get reads, "Compile Error: Expected: End of statement"
Any help is appreciated.
Here is final code that worked for me. Thank you for all of the help.
Private Sub Manager_Change()
Dim dbs As Database, PropID As Integer, ManNam As String, ChangeDate As Date
Set dbs = CurrentDb()
PropID = Me.ID
ManNam = Me.Manager
ChangeDate = Date
dbs.Execute " INSERT INTO tbl_ManagerChangeLog " & "(Property, NewMan, DateChange)VALUES " & "(" & PropID & ", " & ManNam & ", #" & ChangeDate & "#);"
End Sub
You must run a SQL query using Execute funcion from currentDb object, and build the query values concatenating values:
Private Sub Manager_AfterUpdate()
Dim sSQL as String
sSQL = "INSERT INTO tbl_ManagerChangeLog (Property, NewMan, [Date Change]) " & _
"VALUES (" & Me.ID & ",'" & Me.Manager "'," & _
"#" & format(DATE(),"YYYY-MM-DD HH:NN:SS") & "#)"
currentDB.Execute sSQL
End Sub
Try the following VBA to run a sql query.
Private Sub Manager_AfterUpdate()
Dim strSql As String , Db As dao.Database
strSql = "INSERT INTO tbl_ManagerChangeLog (Property, NewMan, [Date Change]) VALUES (Me.ID, Me.Manager, DATE());"
'Use Current Database
Set Db = CurrentDb()
'Run the SQL Query
Db.Execute strSql
End Sub