I have written a VBA code in Access. But, a table or a query does not added to the access. I do not see the results of the VBA code in access.
Option Compare Database
Sub TransformX1()
Dim strSQL As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Set dbs = CurrentDb
strSQL = ""
strSQL = strSQL & "TRANSFORM Sum(BAR1.[TON]) AS SumOfTON " & vbCrLf
strSQL = strSQL & "SELECT BAR1.[MABD], Sum(BAR1.[TON]) AS [Total Of TON] " & vbCrLf
strSQL = strSQL & "FROM BAR1 " & vbCrLf
strSQL = strSQL & "WHERE (((BAR1.[MABD])<1300) AND ((BAR1.[MAGH])<1300) AND ((BAR1.G)=1)) " & vbCrLf
strSQL = strSQL & "GROUP BY BAR1.[MABD] " & vbCrLf
strSQL = strSQL & "PIVOT BAR1.[MAGH];"
Set rst = dbs.OpenRecordset(strSQL)
End Sub
Since your SQL is static, there is no reason to (re)create it in VBA.
Create a query and paste your SQL into this. This will be a crosstab query.
Save it using a name, say, Q1.
Now, create a new query, say Q2, where you use Q1 as source. Adjust query Q2 to be either an append query or a create table query. This query you can run (execute) at any time.
Related
I found this code that allows me to combine all the tables in my Access DB into one big one:
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Set db = currentdb
For Each tdf In db.TableDefs
If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "test") Then
StrSQL = "INSERT INTO " & "test" & " " & _
"SELECT * " & _
"FROM " & tdf.Name & " ;"
DoCmd.RunSQL StrSQL
End If
It works perfectly but I now need this to combine all the tables but one (called Table1). I wanted to ask this question as a comment on that post but I don't have the rep to comment on it.
Bellow is the changes I've tried but haven't worked.
"FROM " & tdf.Name & " WHERE <> Table1;"
I'm trying to insert the current date into a table using VBA in MS Acess. The date gets inserted as 12/30/1899 No matter what I try. Any advise to fix this? Here is my code
Dim StrSQL As String
Dim db As Database
Dim InID As Integer
Dim Inputcasedate As String
Dim InputCaseType_Id As Integer
InID = Me.PgmPart_ID
Inputcasedate = Date
InputCaseType_Id = 1
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & "," & InputCaseType_Id & "," & Inputcasedate & ")"
In MS Access, literal date values must be delimited by pound/numeral/hashtag symbols: #.
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & ", " & InputCaseType_Id & ", #" & Inputcasedate & "#)"
However, like VBA, Access SQL maintains the Date() function. So use this expression inside the SQL statement and avoid the concatenated VBA variable.
StrSQL = "INSERT INTO CaseNotes (PgmPart_ID,CaseType_ID,CaseDate) " & _
"VALUES (" & InID & ", " & InputCaseType_Id & ", Date())"
However, consider the industry best practice with parameterized SQL which MS Access's DAO supports via QueryDefs.Parameters. Doing so, requires no value delimiters like quotes for strings or numerals for dates and aligns data types between app layer (VBA) and database.
Dim StrSQL As String
Dim db As Database
Dim qdef As QueryDef
' PREPARED STATEMENT (NO VBA VARIABLES)
StrSQL = "PARAMETERS ParamInID Long, ParamInputCaseType_Id Long; " & _
"INSERT INTO CaseNotes (PgmPart_ID, CaseType_ID, CaseDate) " & _
"VALUES (ParamInID, ParamInputCaseType_Id, Date());"
' INITIALIZE DAO OBJECTS
Set db = CurrentDb
qdef = db.CreateQueryDef("", StrSQL)
' BIND PARAMETERS
qdef!ParamInID = Me.PgmPart_ID
qdef!ParamInputCaseType_Id = 1
' EXECUTE ACTION
qdef.Execute
Set qdef = Nothing: Set db = Nothing
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.
I have a form with textboxes. I am inserting what the user enters into the textbox into a table. If the user enters an apostrophe in the textbox labeled "Me.ProjectName", I get an error. My code is:
CurrentDb.Execute "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Me.ProjectName & "')"
You should not construct and execute dynamic SQL based on user input. You should use a parameterized query, something like:
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
"INSERT INTO Table1 (ProjectNumber, Title) VALUES (#prjnum, #title)")
qdf.Parameters("#prjnum").Value = ProjectNumber
qdf.Parameters("#title").Value = me.ProjectName
qdf.Execute
You should escape your strings possibly containing quotes by replacing a quote with 2 quotes:
Dim SQL As String
SQL = "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Replace(Me.ProjectName, "'", "''") & "')"
CurrentDb.Execute SQL
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] & "'"