VB the microsoft access database engine could not find the object - vb.net

I'm receiving the following run time error on VB (Excel 10) "the microsoft access database engine could not find the object". The "Database" is a defined named within a worksheet but it wont pick it up. Any ideas would be hugely appreciated!!
Sub ConnectDB()
If cnn.State <> adStateOpen Then
Dim strFileName As String
strFileName = "O:Children's Fund\APS 2014-15\Refrerral - Allocation Database.xlsx"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFileName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
End If
End Sub
Sub CopyData()
ConnectDB
Dim rst As New ADODB.Recordset
Dim CurrentID As Long
Dim vbResult As VbMsgBoxResult
rst.Open "SELECT * FROM [A2:M1000];", cnn, adOpenStatic, adLockReadOnly
If Not rst.EOF Then
rst.MoveLast
CurrentID = rst("RefNumber")
CurrentID = CurrentID + 1
Else
CurrentID = 1
End If
Dim sql As String
sql = "Insert into [Database] (refnumber, surname, FirstName, DOB, ReferrerEmail, PreferredSetting, MotherEmployment, FatherEmployment, OtherEmployment, Other1Employment, Attendance, Exclusions) values ('" & _
CurrentID & "','" & [FormSurname] & "','" & [FormFirstName] & "','" & [FormDOB] & "','" & [FormEmail] & "','" & [FormPreferred] & "','" & [FormMother] & "','" & [FormFather] & "','" & [FormOther] & "','" & [FormOther1] & "','" & [FormAttendance] & "','" & [FormExclusions] & "')"
cnn.Execute (sql)
MsgBox "Record Saved to Database"
DisconnectDB
End Sub
Sub DisconnectDB()
If cnn.State <> adStateClosed Then
cnn.Close
Set cnn = Nothing
End If
End Sub
Many Thanks
Sam

Related

Number of query values and destination fields are not the same. Error in vb.net

I'm using Microsoft Visual Studio 2010 Express and I'm trying to make a enrollment form using VB.NET. This is my code so far:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cardStr As String
Dim formStr As String
Dim birthStr As String
Dim goodmoralStr As String
If cbcard.Checked Then
cardStr = "OK"
Else
cardStr = ""
End If
If cbform.Checked Then
formStr = "OK"
Else
formStr = ""
End If
If cbbirth.Checked Then
birthStr = "OK"
Else
birthStr = ""
End If
If cbgoodmoral.Checked Then
goodmoralStr = "OK"
Else
goodmoralStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection(conStr)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into tblEnroll(StudID,StudLevel,StudFName,StudMName,StudLName,StudGender,StudBirthday,StudNationality,StudContact,StudPOB,StudCitizenship,StudReligion,MomName,MomContact,MomOccupation,DadName,DadContact,DadOccupation,PrevSchool,Card,F137,BirthCertificate) values ('" & txtID.Text & "','" & lbGrade.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & txtLName.Text & "','" & lbGender.Text & "','" & dtpBirthDate.Text & "','" & txtNationality.Text & "','" & txtStudContact.Text & "','" & txtPOB.Text & "','" & txtCitizen.Text & "','" & txtReligion.Text & "','" & txtMom.Text & "','" & txtMomContact.Text & "','" & txtMomOccupation.Text & "','" & txtDad.Text & "','" & txtDadContact.Text & "','" & txtDadOccupation.Text & "','" & txtPrevSchool.Text & "','" & cardStr & "','" & formStr & "','" & birthStr & "','" & goodmoralStr & "')"
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Student Successfully Enrolled!")`
What could be the solution here?
You have one too many columns in your INSERT statement values. The value goodmoralStr does not have a corresponding column to insert into.
As a slight aside, you really should use parameterised SQL in your code to avoid issues with SQL injection.

Automation error using SQL queries in a loop

I'm trying to run a loop through a table that takes relevant information and then inserts it into a VFP9 .dbf table. However, I keep getting an automation error ('-2147217913 (80040e07)'). It seems to run the first time just fine, inserting into a table a single time before erroring out. I've made it print out the string every time with the execution part of the code commented out, but the SQL looks perfectly fine. What is the issue here?
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "DSN=Visual FoxPro Tables;UID=;SourceDB=s:\accounting\db;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For i = 1 To [RawTable].Rows.Count
vStatement = "dong!"
vAccount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("account").Index)
vCardUser = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("card member").Index)
vDate = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("date").Index)
vDesc = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("description").Index)
vAmount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("amount").Index)
MsgBox "INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")"
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")")
Next i
MsgBox "done :)", vbInformation
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
EDIT: Here is an example of what the table will look like.
date receipt description card member account # amount account
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 9.95 41000-000-00
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 33 41000-000-00
06/29/2016 Purchase Employee XXXX-XXXXXX-XXXXX 64 41000-000-00
Visual Foxpro doesn't like receiving dates as just String literals or series of numbers. Try using the CTOD function (Characters to Date) and see if that resolves the problem. The Execute line should look like:
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "',CTOD('" & vDate & "'),'" & vDesc & "'," & vAmount & ")")

Edit/Update datagridview VB form

When I try to edit and update the data in datagriview it comes up with an error message saying Operator '&' is not defined for type 'TextBox' and string "".
please help. Thanks
Here is my code
Private Sub btnaddrecord_Click(sender As Object, e As EventArgs) Handles btnaddrecord.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.IdentificationNotest.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO vehicledefects(Codenumber, vehiclereg, datereported, defects1, repaired1, defects2, repaired2, defects3, repaired3, datefixed) " & _
" VALUES(" & Me.IdentificationNotest.Text & ",'" & Me.vehiclereg.Text & "','" & Me.datereported.Text & "','" & Me.defects1.Text & "','" & Me.repaired1.Text & "','" & _
Me.defects2.Text & "','" & Me.repaired2.Text & "','" & _
Me.defects3.Text & "','" & Me.repaired3.Text & "','" & _
Me.datefixed.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE vehicledefects" & _
" SET Codenumber =" & Me.IdentificationNotest.Text & _
", vehiclereg ='" & Me.vehiclereg.Text & "'" & _
", datereported ='" & Me.datereported.Text & "'" & _
", defects1 ='" & Me.defects1.Text & "'" & _
", repaired1 ='" & Me.repaired1.Text & "'" & _
", defects2 ='" & Me.defects2.Text & "'" & _
", repaired2='" & Me.repaired2.Text & "'" & _
", defects3='" & Me.defects3.Text & "'" & _
", repaired3='" & Me.repaired3.Text & "'" & _
", datefixed='" & Me.datefixed.Text & "'" & _
" WHERE Codenumber =" & Me.IdentificationNotest.Tag
cmd.ExecuteNonQuery()
End If
refreshdata()
Me.btnclear.PerformClick()
cnn.Close()
datefixed.Text = ""
IdentificationNotest.Text = ""
End Sub
In the future, you should also post the line number the error is being thrown on.
The error is telling you that you're doing something like:
dim myString as String = myTextBox & " some more text"
in this case, you would need to do:
dim myString as String = myTextBox.Text & " some more text"
In the code you posted, I wasn't able to find an instance of this - so perhaps its somewhere else in the code. Though, the code was hard to read so I may have missed it.
You may also be aware that this code is susceptible to SQL Injection attacks

Stoping Macro if Connection is Lost

I have a series of codes that run when designated, the first is a connection check. If it is successful then it allows the code to continue, if not it stops it altogether. I am worried however about what happens when the connection is lost after this process. There is data on a local table that is uploaded to our SQL server during this process, if the connection terminates mid download it looks like sometimes the data is still transferred but not if it happens right away.
The second part of the code, deletes all the local tables contents which contain employee information, then downloads the new data so if there were any updates the most recent information is provided.
I am trying to figure out if there is a method or code that can be implemented to tell the query to stop running as soon as connection is lost, or if there is a way to undo it if it happens.
Or would it be a good idea to combine the connection code with the upload and delete codes so it runs every time before it initiates a process?
The connection code that runs at the beginning is:
Public Function StartUp()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
On Error Resume Next
Set cnn = New ADODB.Connection
cnn.Open "Provider=PRO; Data Source=SOURCE; Initial Catalog=CAT;" _
& "User Id=ID; Password=PW;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection with the L&TD SQL Server Database and the CDData table has been uploaded to the server.")
Else
MsgBox ("Cannot connect to SQL Server. Data will be stored locally to CDData Table until application is opened again with an established connection.")
End
End If
On Error GoTo 0
' MsgBox ("Please wait while the database is updating, this may take a moment.")
End Function
As you can see, I placed an END before the END IF so if there is no connection it just ends altogether.
The UPLOAD code is
Public Function Update()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim err As DAO.Error
' Const DestinationTableName = "AC_CDData"
Const ConnectionString = _
"ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=SERV;" & _
"Database=DB;" & _
"UID=ID;" & _
"PWD=PWD;"
Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
Set rs = CurrentDb.OpenRecordset("CDData", dbOpenTable)
qdf.Connect = ConnectionString
Do While Not rs.EOF
qdf.SQL = "INSERT INTO AC_CDData_1(EmployeeID, EmployeeName, Region, District, Function1, Gender, EEOC, Division, Center, MeetingReadinessLevel, ManagerReadinessLevel, EmployeeFeedback, DevelopmentForEmployee1, DevelopmentForEmployee2, DevelopmentForEmployee3, DevelopmentForEmployee4, DevelopmentForEmployee5, Justification, Notes, Changed, JobGroupCode, JobDesc, JobGroup) " & _
"Values (" & _
"'" & rs!EmployeeID & "', " & _
"'" & rs!EmployeeName & "', " & _
"'" & rs!Region & "', " & _
"'" & rs!District & "', " & _
"'" & rs!Function1 & "', " & _
"'" & rs!Gender & "', " & _
"'" & rs!EEOC & "', " & _
"'" & rs!Division & "', " & _
"'" & rs!Center & "', " & _
"'" & rs!ManagerReadinessLevel & "', " & _
"'" & rs!MeetingReadinessLevel & "', " & _
"'" & rs!EmployeeFeedback & "', " & _
"'" & rs!DevelopmentForEmployee1 & "', " & _
"'" & rs!DevelopmentForEmployee2 & "', " & _
"'" & rs!DevelopmentForEmployee3 & "', " & _
"'" & rs!DevelopmentForEmployee4 & "', " & _
"'" & rs!DevelopmentForEmployee5 & "', " & _
"'" & rs!Justification & "', " & _
"'" & rs!Notes & "', " & _
"'" & rs!Changed & "', " & _
"'" & rs!JobGroupCode & "', " & _
"'" & rs!JobDesc & "', " & _
"'" & rs!JobGroup & "')"
qdf.ReturnsRecords = False
On Error GoTo Update_qdfError
qdf.Execute dbFailOnError
On Error GoTo 0
rs.MoveNext
Loop
rs.Close
Set qdf = Nothing
Set cdb = Nothing
Set rs = Nothing
Exit Function
Update_qdfError:
For Each err In DAO.Errors
MsgBox err.Description, vbCritical, "Error " & err.Number
Next
End Function
So is there a way I can modify the Connection code and add it to the update code (minus the message boxes) so if the connection cuts off it will terminate the code?
Did you try out transactions? Wrapping your insert script inside a transaction will not change the database until you've explicitly committed the transaction. If the data connection is lost during the inserts, the commit will never be called, and the SQL Server data won't be changed.
See http://msdn.microsoft.com/en-us/library/office/ff196400%28v=office.15%29.aspx

Excel Macro Error - "User Defined Type Not Defined" - References Grayed out

So I created this code (probably don't even have to show it- but just in case!), have not been able to test it as I get "User defined type not defined" on the first line. I saw that I should set the reference in Tools>References but
the option is grayed out....
Sub UploadDistributors()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
strConn = "Provider=SQLOLEDB-Removed for security-Network Library=DBMSSOCN"
cnn.Open strConn
Dim k
k = 0
For i = 1 To 352
sSQL = "INSERT INTO DistributorsNP (CompanyName, address, city, state, zip, phone, tollfree) VALUES ("
'CompanyName
sSQL = sSQL & Sheet1.Range("B" & i).Value & ","
'address
sSQL = sSQL & Sheet1.Range("C" & i).Value & ","
'city
sSQL = sSQL & Sheet1.Range("D" & i).Value & ","
'state
sSQL = sSQL & Sheet1.Range("E" & i).Value & ","
'zip
sSQL = sSQL & Sheet1.Range("F" & i).Value & ","
'phone
sSQL = sSQL & Sheet1.Range("G" & i).Value & ","
'tollfree
sSQL = sSQL & Sheet1.Range("H" & i).Value & ","
sSQL = sSQL & ")"
rs.Open sSQL, cnn, adOpenStatic, adLockReadOnly, adCmdText
rs.Close
Next
End Sub
Guessing you've pressed stop in the editor and are no longer in break mode...?