With an Access VBA, I am trying to load a file from a directory to the table [table name] in the field [field name] which Data Type is Attachment.
The problem is that I get the error Invalid field data type.
The code is the following.
Dim SQL As String
SQL = " SELECT * FROM [table name] WHERE ID = '10'"
Dim VESRecordSet As Recordset
Set VESRecordSet = CurrentDb.OpenRecordset(SQL)
VESRecordSet![field name].LoadFromFile "D:\Documents\file.vsd"
You have made multiple errors:
To work with attachments, you should use the DAO.RecordSet2 object
You need to open the child recordset containing the file data before you can use .LoadFromFile
You should use .Edit and .Update when editing and updating a recordset
Final code:
Dim SQL As String
SQL = " SELECT * FROM [table name] WHERE ID = '10'"
Dim VESRecordSet As DAO.Recordset2
Dim rsAttachments As DAO.Recordset2
Set VESRecordSet = CurrentDb.OpenRecordset(SQL)
VESRecordSet.Edit
Set rsAttachments = VESRecordSet![field name].Value
rsAttachments.AddNew
rsAttachments.Fields("FileData").LoadFromFile "D:\Documents\file.vsd"
rsAttachments.Update
rsAttachments.Close
VESRecordSet.Update
VESRecordSet.Close
Related
I have a query that contains two fields, 'From' and 'To'. The from and to hold data that has the complete files paths of files that I want to rename. How do I loop through the query and actually rename the files? This is my code below but it's not working:
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "select * from qryImagesToRename"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
Name .Fields("From") as .Fields("To")
rs.MoveNext
Loop
Where am I going wrong? - I receive a Compile error "Expected user-defined type, not project" and it highlights the line:
Dim db As Database
You miss the recordset object:
Name rs.Fields("From").Value As rs.Fields("To").Value
I am attempting to iterate a table by using recordset. This is the syntax that I have, but my issue is that if I do a Debug.Print for rsInsert!StoreNumber it is always blank! Now if I do a Debug.Print for storenumfield it contains a value. What would be the proper way to use a variable in the Insert statement like below?
Dim rsSelect As DAO.Recordset, rsInsert As DAO.Recordset, db As DAO.Database
Set db = CurrentDb
Set rsSelect = db.OpenRecordset("Select DISTINCT [_SpreadsheetImport]." & storenumfield & " FROM [_SpreadsheetImport]")
Set rsInsert = db.OpenRecordset("NewTable")
Do While Not rsSelect.EOF
rsInsert.AddNew
rsInsert!StoreNumber = rsSelect!& storenumfield
rsInsert![VID] = ConcatRelated("[VID]", "[_SpreadsheetImport]", "[snF] =" & rsSelect!snF)
rsInsert.Update
rsSelect.MoveNext
Loop
Original syntax written by #Erik von Asmuth
-> link to profile
https://stackoverflow.com/users/7296893/erik-von-asmuth
-> with full post here
Character Limit On ConcatRelated() Function
I am writing an Access 2007 application that sends an email and selects the body of the email based on a variable. I have each of the optional emails stored in a table. My current code looks like this:
Dim MyMail As Outlook.MailItem
Dim WhatEmail As Integer
Set WhatEmail = 3
MyMail.Body = "SELECT [Emails].[Body] FROM [Emails] WHERE EmailNumber = WhatEmail"
My Emails table has columns EmailNumber (integer) and Body.
I am receiving a Compile error:
Expected: line number or label or statement or end of statement.
Your code as it is will not be doing anything meaningful; your "SELECT... " statement is merely a string, and (if the code did actually work), it would set the message body to exactly that: "SELECT [Emails].[Body] ...".
Presumably not what you want at all!
Instead we must use DAO (or similar) to get the message body from our database.
Public Sub sendMail()
Dim WhatEmail As Integer
Dim strSQL As String, strMessageBody As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim oApp As Outlook.Application
Dim oMail As MailItem
WhatEmail = 2
strSQL = "SELECT [Body] FROM [Emails] WHERE EmailNumber = " & WhatEmail
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
If (rs.EOF And rs.BOF) Then
Debug.Print "No matching email found"
Exit Sub
End If
rs.MoveFirst
strMessageBody = rs![Body]
rs.Close
Set rs = Nothing
Set db = Nothing
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = strMessageBody
oMail.Subject = "subject of email"
oMail.To = "name#domain.com"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End Sub
Notes on changes from your original:
The variable WhatEmail is now outside the quotes of the string, so VBA uses the value of the variable rather than the text "WhatEmail". This means we set strSQL to
"SELECT [Body] FROM [Email] WHERE EmailNumber = 2"
(or whatever number you have set your WhatEmail variable as), rather than
"SELECT [Body] FROM [Email] WHERE EmailNumber = WhatEmail"
We then load a recordset using DAO with this SQL string as the parameter. It will hopefully return just one record (the correct line from our Emails table) - but if something has gone wrong and there is no matching EmailNumber in the table, we will get a message in the Immediate window ("No matching email found") and the procedure will exit.
Otherwise, we look at the record in the table (rs.MoveFirst) and then get the Body field of it with rs![Body].
Note: I have assumed that there will be at most one entry in the Emails table with a matching EmailNumber - in my database it is the primary key.
So I am essentially trying to link a table via DAO from an ACCDB that is password-encrypted into the DB I am working in. The premise of what I am doing is that the data is sort of "user sensitive" so I do not want to let every user have access to this table in my front end (have the front-end/back-end split), only specific users. What I would like to do is to check the username of the computer, then allow the front-end to link to the data if the username is correct:
Select Case Environ("username") 'select case user environment name
Case "jsmith" 'if username is jsmith then
Set db = DAO.OpenDatabase("Audit.accdb", False, False, _
";pwd=adaudit12") 'create connection to my other db
Set tbl = db.TableDefs(14) 'selects the table via index
CurrentDb.TableDefs.Append tbl 'create a link to my current DB with this table (throws ex here)
Case Else
End Select
This returns runtime error '3367' Cannot Append. An object with that name already exists in the collection.
So I thought to do this:
For Each tbl In CurrentDb.TableDefs
Msgbox tbl
Next tbl
But the table doesnt exist in my database, so what should I do?
Take a closer look at how you're examining the table names in CurrentDb. This line throws error #13, "Type mismatch", on my system:
Msgbox tbl
I think you should ask for the TableDef.Name instead:
Msgbox tbl.Name
However, I'm not sure that's the only problem here. You seem to be trying to link to a table in another db file by copying that TableDef and adding it to CurrentDb.TableDefs. IF you can make that work, it won't give you a link to the source table, it would make a new copy in CurrentDb. But I'm skeptical whether it can work at all.
You could create a new TableDef object, set its Name, Connect, and SourceTableName properties, then append it to CurrentDb.TableDefs. Include the database password in the Connect property.
Here is code tested in Access 2007.
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Dim strDbFile As String
Dim strLinkName As String
Dim strPassword As String
Dim strSourceTableName As String
strDbFile = "C:\share\Access\MyDb.accdb"
strPassword = "foo"
strSourceTableName = "Contacts"
strLinkName = "link_to_contacts"
strConnect = "MS Access;PWD=" & strPassword & _
";DATABASE=" & strDbFile
Debug.Print strConnect
Set db = CurrentDb
Set tdf = db.CreateTableDef
tdf.Connect = strConnect
tdf.SourceTableName = strSourceTableName
tdf.Name = strLinkName
db.TableDefs.Append tdf
Set tdf = Nothing
Set db = Nothing
Tables and queries share the same name space in MS Access. Chances are you have a query with the same name as the table you are trying to link.
Also, Environ("username") is easily spoofed. Consider using the API function GetUserName instead. Of course, if you need real security you'll want to upgrade your back-end to SQL Server (Express) or some other RDBMS.
In Access 2010 I need to be able to click a command button that will run a query that returns a small two field recordset. Then put the second field in that recordset into a string variable.
This string variable is a link to a word document on the network. the second part of the code will then open the word document.
Any help is GREATLY appreciated.
I am getting the Error: "Object variable or With block variable not set"
My Code looks like this:
`Option Compare Database
Private Sub cmdCESpec_Click()
On Error GoTo Err_cmdCESpec_Click
Dim db As Database
Dim rs As DAO.Recordset
Dim s As String
Dim specSheet As String
s = "SELECT p.PartNum, p.CE_SpecSheet FROM tblParts p WHERE p.PartNum = '" & [Forms]![frmSpecSheet]![cboPartNum] & "'" 'Chooses the correct Spec Sheet.
Set rs = db.OpenRecordset(s)
specSheet = rs.Fields("CE_SpecSheet") 'Chooses the Spec Sheet Field
rs.Close
Dim oApp As Object
Set oApp = CreateObject("Word.Application")
oApp.Visible = True
With oApp
.Documents.Open (specSheet)
End With
Exit_cmdCESpec_Click:
Exit Sub
Err_cmdCESpec_Click:
MsgBox Err.Description
Resume Exit_cmdCESpec_Click
End Sub
After dissecting your code.. this:
"..WHERE (((tblParts.PartNum)=[Forms]![frmSpecSheet]![cboPartNum]));"
embeds the words Forms!etc into your sql-statement, it doesn't insert the combo-box value into the statement.
You need to take the form reference out of the string:
Dim db As Database
Dim rs As Recordset
Dim s As String
Dim specSheet As String
s = "SELECT tblParts.PartNum, tblParts.CE_SpecSheet FROM tblParts WHERE " _
& "tblParts.PartNum=" & [Forms]![frmSpecSheet]![cboPartNum]
'Chooses the Correct Spec Sheet
Set db = CurrentDb
Set rs = db.OpenRecordset(s)
specSheet = rs.Fields("CE_SpecSheet")
'Chooses the Spec Sheet Field
rs.Close
Dim oApp As Object
Set oApp = CreateObject("Word.Application")
oApp.Visible = True
With oApp
.Documents.Open ("specSheet")
End With
If the combobox's value is text then you'll need to also surround this with apostrophes.
You also don't need to SELECT the field tblParts.PartNum, you can just refer to it in the WHERE clause.
You haven't posted much information but what I gather you're looking for is Recordset
Dim db As Database
Dim rs As Recordset
Dim s As String
Dim myString As String
s = "SELECT * FROM myTable1;" 'Replace with the SQL you need
Set db = CurrentDb
Set rs = db.OpenRecordset(s)
myString = rs.Fields("myFieldName1") 'Replace myFieldName with the appropriate field name
rs.Close