VBA compile error object required - vba

I have inherited a vba project and have been recently getting my feet wet with vba development. I have enountered an error Compile Error Object Required when running a portion of code that I have recently made edits to. Since it's a compile error, I cant see at runtime exactly which line is throwing the error. The only code I have modified is the ElseIf block in the following code... all help is appreciated.
If tableType = 1 Then 'Resident/Local
Set db = CurrentDb
db.Execute "ALTER TABLE [" & TableName & "] ALTER COLUMN [" & KeyColumn & "] COUNTER(1,1)"
ElseIf tableType = 4 Then
Set conn = New ADODB.Connection
Dim connectionString As String
Set connectionString = DLookup("[Connect]", "[MSysObjects]", "[Name] = '" & TableName & "'")
conn.connectionString = connectionString
conn.Open
Dim cmd As ABODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandText = "ALTER TABLE [" & TableName & "] ALTER COLUMN [" & KeyColumn & "] COUNTER(1,1)"
cmd.Execute
conn.Close
Else 'Linked Table
Set wsp = DBEngine.Workspaces(0)
Set db = wsp.OpenDatabase(DLookup("[Database]", "[MSysObjects]", "[Name] = '" & TableName & "'"))
db.Execute "ALTER TABLE [" & TableName & "] ALTER COLUMN [" & KeyColumn & "] COUNTER(1,1)" 'reset the autonumber column value
End If

Remove the Set from this line:
Set connectionString = DLookup("[Connect]", "[MSysObjects]", "[Name] = '" & TableName & "'")
Set is only used for assigning object references, and connectionString is a String.
For future reference, the VBE will highlight the line with the compile error if you use Debug->Compile from the menu.

Normally if I was writing and if statement o would have it like this
If tableType = 1 Then 'Resident/Local
Set db = CurrentDb
db.Execute "ALTER TABLE [" & TableName & "] ALTER COLUMN [" & KeyColumn & "] COUNTER(1,1)"
Else
If tableType = 4 Then
give that a bash. May just bee the formatting error

Related

Data Type Mismatch error while using the SQL Update query

I am using SQL update query in VBA and I am getting the datatype mismatch error. I know that error is basically because of the column spare part. The spare part column contains numeric and alphanumeric values.
Public Function UpdateDistinctColumnFRNumberBasis()
StrInvoiceNumber = "109839-01"
FRSparepartNumber = "FT7119907459"
MergedInvoiceFile = "/test.xlsx"
Dim objConn As Object
Dim objRecordSet As Object
Set objConn = CreateObject("ADODB.Connection")
Set objRecCmd = CreateObject("ADODB.Command")
Set objRecCmd_Update = CreateObject("ADODB.Command")
objConn.Open ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
MergedInvoiceFile & ";Extended Properties=""Excel 8.0;""")
strSQL = " Update [Tabelle1$] SET [Status] = 'Include' Where " & _
"([RECHNR] ='" & StrInvoiceNumber & "' AND [Sparepart] = " & FRSparepartNumber & ")"
objConn.Execute strSQL
objConn.Close
End Function
As commented, the partnumber is text, thus it must be quoted in the SQL:
FRSparepartNumber = "FT7119907459"
' snip
strSQL = "Update [Tabelle1$] SET [Status] = 'Include' Where " & _
"([RECHNR] = '" & StrInvoiceNumber & "' AND " & _
"[Sparepart] = '" & FRSparepartNumber & "')"

a temp table for updating the values, getting error message saying 'temp table0' already exists, how to navigate this?

I am using a VBA query in Access database for creating a temp table for updating the values, however I am getting error message saying 'temp table0' already exists, how to navigate this?
I am getting error message in 'CurrentProject.Connection.Execute strSql'
rs2.Close 'Close the recordset
Set rs2 = Nothing 'Clean up
'Create temporary tables
Dim tableFlag As String
tableFlag = "Treaty"
For x = 1 To 2
If (rs1![Prems/Claims] = "Premium") Then
If (tableFlag = "Treaty") Then
strSql = "SELECT [Premiums " & tableFlag & "].ID, [Premiums " & tableFlag & "].[Pricing Segment]"
For i = 0 To columnsCount - 1 ' loop through all boolean atributes
strSql = strSql & ", [Premiums " & tableFlag & "].[" & boolAtrName(i) & "]"
Next
strSql = strSql & " INTO [tempTable " & tablesCount & "] FROM [Premiums " & tableFlag & "] WHERE [GDS Version] = " & rs1!ID & ";"
'Execute temporary table string
CurrentProject.Connection.Execute strSql
'Add column percentage to table
CurrentDb.Execute "ALTER TABLE [tempTable " & tablesCount & "] ADD COLUMN Percentage double, Identifier Text"
'Update values in column percentage
Set rs2 = CurrentDb.OpenRecordset("SELECT * FROM [tempTable " & tablesCount & "];")

Why is an action query not working in access VBA?

I tested an UPDATE query in Access's query design, and it works, but when I try to use it in my module, I get the error:
Invalid SQL statement; expected... or 'UPDATE'.
My query:
strSql = "UPDATE " & rs.Fields("tableName") & _
" SET " & rs.Fields("foreignKeyName") & " = " & rsContacts.Fields("contactId") & _
" WHERE contactId = " & ContactID
rs: a table that has tableName, foriegnKeyName of the tables to update
rsContacts: a list of contactIds (currently standing on a particular one).
The actual string comes out like this:
UPDATE myTable SET ContactId = 5 WHERE contactId = 2
If the query works, and it is an action query, why am I getting this error?
This is my full code:
Public Sub updateChildTables(ByVal ContactID As Long, ByVal CompanyID As Long)
Dim strSql As String
Dim rs As Recordset
Dim rsPending As Recordset
strSql = "SELECT contactID FROM contacts _
WHERE companyId = " & CompanyID & " and contactId <> " & ContactID
Set rs = CurrentDb.OpenRecordset(strSql)
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
strSql = "SELECT * FROM childTables"
Set rsChild = CurrentDb.OpenRecordset(strSql)
rsChild.MoveFirst
Do While Not rsChild.EOF
strSql = "UPDATE " & rsChild.Fields("tableName") & " SET " & rsChild.Fields("foreignKeyName") & " = " & rs.Fields("contactId") & " WHERE contactId = " & ContactID
DoCmd.RunSQL strSql
rs.moveNext
Loop
rsChild.Close
Set rsChild = Nothing
End If
Here is my idea for debugging and possibly even resolving this.
Create a query from within Access normally -- name it UpdateMyTable, for the sake of this example.
Then, rather than using the DoCmd, actually execute this specific query from your VBA.
Dim qry As QueryDef
strSql = "UPDATE " & rsChild.Fields("tableName") & " SET " & _
rsChild.Fields("foreignKeyName") & " = " & _
rs.Fields("contactId") & " WHERE contactId = " & ContactID
Set qry = CurrentDb.QueryDefs("UpdateMyTable")
qry.SQL = strSql
qry.Execute
The big advantage of this is that you can very easily debug this from within Access to both see the rendered SQL and manually run it / tweak it.

Append queried Recordset to Table in Access

I am querying Active Directory to list Users and other fields in Access. Is there a way to append my queried results into an existing table? Currently I am trying to use INSERT INTO but having issues with my Object variable not being set or block variable.
Private Sub Command0_Click()
Dim objRecordSet As Object
Dim objCommand As Object
Dim objConnection As Object
Dim dbs As Database
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Sort On") = "whenCreated"
objCommand.CommandText = _
"SELECT Name,Title,PhysicalDeliveryOfficeName,WhenCreated,Mail FROM 'LDAP://OU=Standard Users,OU=Active Users,OU=All Users,DC=contoso,dc=local' WHERE objectCategory='user'"
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
dbs.Execute " INSERT INTO ADUsers" & "(Name,Title,Site,Created,Email) VALUES " & "(objRecordSet.Fields('Name').Value,objRecordSet.Fields('Title').Value,objRecordSet.Fields('physicalDeliveryOfficeName').Value,objRecordSet.Fields('whenCreated').Value,objRecordSet.Fields('Mail').Value);"
dbs.Close
Debug.Print objRecordSet.Fields("Name").Value; "," & objRecordSet.Fields("Title").Value; "," & objRecordSet.Fields("physicalDeliveryOfficeName").Value; "," & objRecordSet.Fields("whenCreated").Value; "," & objRecordSet.Fields("Mail").Value
objRecordSet.MoveNext
Loop
End Sub
Everything inside doublequotes " is interpreted as string not as code and strings (the values of objRecordSet.Fields("myFieldName").Value) have to be quoted in insert statement.
dim strSQLInsert as String
strSQLInsert = "INSERT INTO ADUsers(Name,Title,Site,Created,Email) VALUES ('" & _
objRecordSet.Fields("Name").Value & "','" & _
objRecordSet.Fields("Title").Value & "','" &
objRecordSet.Fields("physicalDeliveryOfficeName").Value & "','" & _
objRecordSet.Fields("whenCreated").Value & "','" & _
objRecordSet.Fields("Mail").Value & "');"
Debug.Print strSQLInsert
dbs.Execute strSQLInsert
Store your sql statements in a string, then you can check it with Debug.Print.
Consider a parameterized query using querydefs to avoid the need of quotes. Also be sure to initialize the database object which may be your main issue: set dbs = CurrentDb.
...
Dim strSQL As String
Set dbs = CurrentDb
strSQL = "PARAMETERS NameParm TEXT(255), TitleParam TEXT(255), SiteParam TEXT(255)," _
& " CreatedParm Date, EmailParam TEXT(255);" _
& " INSERT INTO ADUsers (Name, Title, Site, Created, Email)" _
& " VALUES ([NameParm], [TitleParam], [SiteParam], [Created], [Email]);"
Do Until objRecordSet.EOF
Set qdef = dbs.CreateQueryDef("", strSQL)
qdef!NameParam = objRecordSet![Name]
qdef!TitleParam = objRecordSet![Title]
qdef!SiteParam = objRecordSet![PhysicalDeliveryOfficeName]
qdef!CreatedParam = objRecordSet![WhenCreated]
qdef!EmailParam = objRecordSet![Mail]
qdef.Execute (dbfailOnError)
Set qdef = Nothing
objRecordSet.MoveNext
Loop

Update query not updating values in the table using Access

I am trying to run a simple update query which should obtain a value from a form and update an already existing table. This is done using VBA. On executing no error message is shown but the table isn't updated with the new value from NI. The code is as follows.
strsql = "UPDATE t_datefromform SET "
strsql = strsql & "[txtmonth] = '" & [Forms]![SupplierScorecard].[txtMonth] & "'"
Debug.Print strsql
CurrentDb.Execute strsql
set [txtmonth] is an input parameter
use
strsql = "Update t_datefromform set txtmonth = '" & [Forms]![SupplierScorecard].[txtMonth] & "'"