How to add data to attachment dialog box of a form using VBA? - sql

I am trying to add an attachment that is found within the current database to a control on the current form:
I have a form that contains both a combo box ("cmb") and an attachment control ("attachctrl").
The user shall be able to choose a value in the combo box and the corresponding attachment shall be added to the attachment control.
I am using an SQL query to get the recordset from the table containing the attachments. I am able to get some data (e.g. the file name, type, URL and the data).
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim intResult As Integer
Dim strSQL As String
Dim existingEntry
Set db = CurrentDb
strSQL = "SELECT [Analysis1] FROM [tblAnalysis] WHERE [ID] = '" & Me.cmb.Value & "'"
Set rs = db.OpenRecordset(strSQL)
I can then access the fields within the recordset as:
fileName = rs(0).Value.fileName
fileType = rs(0).Value.FileType
fileData = rs(0).Value.FileData
However, how can I add the data to the corresponding fields of the attachment control?
When I try to manually write the data to the fields I get an error message, that I am not allowed to write to the field in question:
Me.attachctrl.fileName = rs(0).Value.fileName 'not working
Me.attachctrl.FileType = rs(0).Value.fileName 'not working
Me.attachctrl.FileURL = rs(0).Value.FileURL 'not working
Also: I can't find a field that would take the actual data of the attachment. Where do I assign the data to?

Related

"NotOnList" event not recognizing that new data has, in fact, been added

This used to work but now it doesn't. Did Microsoft change something?
I'm attempting to understand the behavior of a combo box in MS Access. I created a table named "Colors" with 2 fields: ID (Autonumber, primary key) and Color (short text). I made a form with a combobox with "LimitToList" set to Yes. The Row Source is the table "Colors". For the NotInList event I have the following code:
Private Sub Colors_NotInList(NewData As String, Response As Integer)
Dim rst As DAO.Recordset
If MsgBox(NewData & " is not in list. Add it?", vbOKCancel) = vbOK Then
Response = acDataErrAdded
Set rst = CurrentDb.OpenRecordset("Colors")
With rst
.AddNew
!Color = NewData
.Update
End With
Else
Response = acDataErrContinue
ctl.Undo
End If
End Sub
If I enter a color not in the table I get the prompt to add it to the list. On clicking OK I get the Access error that I must select an item on the list. The new color I just entered does appear on the list and if I select it everything works fine. But I didn't used to have this second step of selecting it after it's been entered.
I've spent way to much time on what should be a simple task. Can anyone help? Thanks!

Setting field 'InputMask' properties programmatically

I have an Access database divided into front and back ends.
I need to modify the value of a property associated to one of the fields in a table programmatically. I do remember achieving something similar years ago, but that was for forms.
It seems that the properties of a table can only be set at design time; any attempt to modify the values using code (myField.Properties("InputMask").Value = "000000") causes an error.
All in all, there are about 40 or 50 tables in a batch of roughly 80 that have a particular type of field that has to be changed, so I'd rather do this using code than manually. Could anyone suggest a method for doing this using VBA, please?
Presently I've looked at dropping and recreating the field using CurrentDb.Execute sqlString, but I'd like to retain the InputMask property if at all possible.
The original database is a 2002/3 format, but I'm editing this in Access 2010.
I got the following code to work. It will change the InputMask of the specified Table and Field....
Option Compare Database
Option Explicit
Sub Test_It()
Dim WGD
WGD = Resize_And_AddInputMask("Table3", "SomeNbr")
End Sub
' Modified version of code found at: http://www.tek-tips.com/viewthread.cfm?qid=1708626
Public Function Resize_And_AddInputMask(ByVal someTableName As String, ByVal someZCField As String)
Dim db As DAO.Database
Dim td As DAO.TableDef
Dim fd As DAO.Field
Dim prp As DAO.Property
Set db = CurrentDb
Set td = db.TableDefs(someTableName)
Set fd = td.Fields(someZCField)
fd.Properties("InputMask") = "000099"
fd.Properties.Refresh
db.TableDefs.Refresh
Set prp = Nothing
Set fd = Nothing
Set td = Nothing
Set db = Nothing
End Function

Connect to a specific lotus notes database/documen via vba

I can connect to lotus notes via the following code. So basically I connect to the database: CLASTNAME/O=TEST/C=US.nsf
Set oSession = CreateObject("Notes.NotesSession")
Server = oSession.GetEnvironmentString("MailServer", True)
UserName = oSession.UserName
MailDbName = Left$(UserName, 1) & Right$(UserName, (Len(UserName) - InStr(1, UserName, " "))) & ".nsf"
'Open the mail database in notes
Set db = oSession.GETDATABASE("", MailDbName)
Set view = db.GetView("Customers") //ERROR
However, I want to connect to a specific database, which I have. Here is the document link:
<NDL>
<REPLICA C1451C8A:00575D55>
<VIEW OD3B89A25B:7D1FR7SA-OM4923732F:011L111C>
<NOTE OFAAAA64WE:GH1Q0W0W-IUZ0987MNB:2222F4LÖ>
<HINT>CN=ZZZUSDMS09/O=ZZZ/C=US</HINT>
<REM>Database 'UserName', View 'Customers', Document 'AG: A list of all company customers, Jannuary 9, 2009'</REM>
</NDL>
This is what I tried:
Sub notesBB()
'Const DATABASE = ""
Dim r As Integer
Dim i As Integer
Dim db As Object
Dim view As Object
Dim Entry As Object
Dim nav As Object
Dim oSession As Object 'The notes session
Dim nam As Object ' notes username
Dim v() As Variant ' to hold the subtotal values
Dim bills(12, 16) ' 12 months, 16 departments
r = 1
Worksheets(1).Range("A1:Z99").Clear
'##############################
'Start a session to notes
Set oSession = CreateObject("Notes.NotesSession")
Server = oSession.GetEnvironmentString("MailServer", True)
UserName = "CN=ZZZUSDMS09/O=ZZZ/C=US" 'oSession.UserName
CustomerDbName = "CZZZUSDMS09/O=ZZZ/C=US" & ".nsf"
'Open the mail database in notes
Set db = oSession.GETDATABASE("", CustomerDbName)
Set view = db.GetView("OD3B89A25B:7D1FR7SA-OM4923732F:011L111C")
view.AutoUpdate = True // here I get an error
Set nav = view.CreateViewNav
Set Entry = nav.GetFirst
Do Until Entry Is Nothing
If Entry.isCategory Then
r = r + 1
v = Entry.ColumnValues
For i = 1 To 16
bills(v(0), i) = v(4 + i)
Cells(4 + r, 2 + i) = bills(v(0), i)
Next
End If
Set Entry = nav.getNextCategory(Entry)
DoEvents
Loop
End Sub
However, as you can see I get an error hee: view.AutoUpdate = True // here I get an error
How to connect to this database via vba?
I really appreciate your answer!
Well, this doesn't look right:
CustomerDbName = "CZZZUSDMS09/O=ZZZ/C=US" & ".nsf"
'Open the mail database in notes
Set db = oSession.GETDATABASE("", CustomerDbName)
You're just appending ".nsf" to the user's fully disntinguished name in canonical form, and that would be an extremely unusual naming convention for databases on a server. Also, earlier in your code you retrieved the server name, but here you're specifying "" for the server name instead of using what you had retrieved, so the result is that the code will try to open the database on the local machine.
The NDL file is giving you the ReplicaID of the database here:
<REPLICA C1451C8A:00575D55>
You can use the OpenByReplicalID method instead:
repID = "C1451C8A00575D55" ' note that the : is removed
'Open the database by replica id
set db = new NotesDatabase("","")
If db.OpenByReplicaID( , "85255FA900747B84" ) Then
Print( db.Title & " was successfully opened" )
Else
Print( "Unable to open database" )
End If
The next problem, though, is that the NDL file is giving the view's UNID, not its name
<VIEW OD3B89A25B:7D1FR7SA-OM4923732F:011L111C>
There is no call in the Notes COM API that can retrieve a view by its UNID; you need the name for that. But do you really need to get the view? The NDL gives you the UNID of the document, here:
<NOTE OFAAAA64WE:GH1Q0W0W-IUZ0987MNB:2222F4LÖ>
So if your goal is to just get the specific document specified in the NDL, you can use a call to GetDocumentByUNID. Note, however that the actual UNID consists of only the 17 chars to the right of OF in the above tag, minus the : char. So your code would look like this:
unid = "AAAA64WEGH1Q0W0W" ' see note below!!
Set doc = db.GetDocumentByUnid(unid)
BTW, that UNID does not look legal. The chars should be hex, and the W, Q, and G are not. I'm going on the assumption that you (or someone) deliberately obfuscated the data in your NDL file.
If you do need to access the view, the NotesNoteCollection class may provide a way to get there, but it will not be trivial.
Finally, you may find this code from Stepehn Wissel helpful.
Specify the name of the view instead:
Set view = db.GetView("Customer")
Nice to see my code getting recycled ! it seems to me that you aren't using the correct database and view names. Are they not
Database 'UserName', and View 'Customers' ? (from your link). Whatever - when your XL VBA crashes out, in the Debug - Locals window, look for the object(s) that you have tried to instantiate with the SET command. If they show up as "nothing", you've got the SET command(s) wrong and trying to use the failed object (view) then crashes on the following line.
If your servername is "Yoda" I'd guess you need
Set db = session.getdatabase("Yoda", "Username.nsf")
Set view = db.GetView("Customers")

Too few parameters in OpenRecordset code

I have two sets of code, that are the same I just change variables to another set that exist and now with the ones I changed I get an error saying "Run-time error '3061': Too few parameters. Expected 6."
This is the changed code:
Dim rec As Recordset
Dim db As Database
Dim X As Variant
Set db = CurrentDb
Set rec = db.OpenRecordset("UnitMoreInfoQ")
Const msgTitle As String = "Open Explorer"
Const cExplorerPath As String = "C:\WINDOWS\EXPLORER.EXE"
Const cExplorerSwitches As String = " /n,/e"
cFilePath = rec("ProjFilePath")
It highlights this line:
Set rec = db.OpenRecordset("UnitMoreInfoQ")
This is the first code:
Dim rec As Recordset
Dim db As Database
Dim X As Variant
Set db = CurrentDb
Set rec = db.OpenRecordset("ProjectMoreInfoQ")
Const msgTitle As String = "Open Explorer"
Const cExplorerPath As String = "C:\WINDOWS\EXPLORER.EXE"
Const cExplorerSwitches As String = " /n,/e"
cFilePath = rec("ProjFilePath")
As you can see, the line has the same amount of parameters:
Set rec = db.OpenRecordset("ProjectMoreInfoQ")
This has gotten me quite confused for awhile because of this. How do I fix this error?
I didn't get the same result as you when testing your db, and I still don't understand the difference. However, maybe we can still get you something which works in spite of my confusion.
The query contains 6 references to form controls, such as [Forms]![WorkOrderDatabaseF]![Text71]. Although you're certain that form is open in Form View when you hit the "too few parameters" error at db.OpenRecordset("UnitMoreInfoQ"), Access doesn't retrieve the values and expects you to supply them.
So revise the code to supply those parameter values.
Dim rec As DAO.Recordset
Dim db As DAO.database
Dim prm As DAO.Parameter
Dim qdf As DAO.QueryDef
Dim X As Variant
Set db = CurrentDb
'Set rec = db.OpenRecordset("UnitMoreInfoQ")
Set qdf = db.QueryDefs("UnitMoreInfoQ")
For Each prm In qdf.Parameters
prm.value = Eval(prm.Name)
Next
Set rec = qdf.OpenRecordset(dbOpenDynaset) ' adjust options as needed
I'm leaving the remainder of this original answer below in case it may be useful for anyone else trying to work through a similar problem. But my best guess is this code change will get you what you want, and it should work if that form is open in Form View.
Run this statement in the Immediate window. (You can use Ctrl+g to open the Immediate window.)
DoCmd.OpenQuery "UnitMoreInfoQ"
When Access opens the query, it will ask you to supply a value for the first parameter it identifies. The name of that parameter is included in the parameter input dialog. It will ask for values for each of the parameters.
Compare those "parameter names" to your query's SQL. Generally something is misspelled.
Using the copy of your db, DoCmd.OpenQuery("UnitMoreInfoQ") asks me for 6 parameters.
Here is what I see in the Immediate window:
? CurrentDb.QueryDefs("UnitMoreInfoQ").Parameters.Count
6
for each prm in CurrentDb.QueryDefs("UnitMoreInfoQ").Parameters : _
? prm.name : next
[Forms]![WorkOrderDatabaseF]![Text71]
[Forms]![WorkOrderDatabaseF]![ClientNameTxt]
[Forms]![WorkOrderDatabaseF]![WorkOrderNumberTxt]
[Forms]![WorkOrderDatabaseF]![TrakwareNumberTxt]
[Forms]![WorkOrderDatabaseF]![WorkOrderCompleteChkBx]
[Forms]![WorkOrderDatabaseF]![WorkOrderDueDateTxt]
Make sure there is a form named WorkOrderDatabaseF open in Form View when you run this code:
Set rec = db.OpenRecordset("UnitMoreInfoQ")
Does the [UnitMoreInfoQ] query execute properly on its own? If you mistype a field in access it will treat that field as a parameter.
ProjectMoreInfoQ and UnitMoreInfoQ are different queries... it sounds like one takes 6 parameters and the other doesn't. Look at the queries in Access and see if either have parameters defined.

Excel drop down values from a SQL Server source

I am trying to get a cell drop-down values in Excel from a SQL Server. I don't want to use the method of putting all the data to another sheet and the use data validation to control the drop down values. That always give my a bunch of empty lines towards the end since I want to make sure I have room for any addition in the DB.
Is there a way to retrieve the drop-down values directly from SQL Server? Using a statement something like:
Select name from employees
Thanks for your help...
Use ADODB to retrieve the values you want, and use the retrieved values to populate a dropdown shape in Excel which you can create dynamically.
In a similar situation, since the source data was basically static, I populated a global array from an ADODB recordset when the application started and used that array when populating the items in the dropdown. Here's a snippet of that code:
Dim InstrumentIDs() As String
Dim InstrumentIDReader As Integer
Dim InstrumentIDCount As Integer
Public PositionRange As String
Public Sub GetInstrumentIDs()
'
'Populate InstrumentIDs array from current contents of Instrument table in EMS database
'
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sql As String
Dim loader As Integer, sn As String
InstrumentIDReader = 0
On Error GoTo GetInstrumentError
conn.ConnectionString = "Provider=sqloledb; Data Source=myServer; Initial Catalog=myDatabase; User ID=myUser;Password=myPassword"
conn.Open
sql = "Select Count([SerialNo]) As [Number] From [Instrument]"
rs.Open sql, conn, adOpenStatic
InstrumentIDCount = CInt(rs![Number])
ReDim InstrumentIDs(InstrumentIDCount - 1)
rs.Close
sql = "Select [SerialNo] From [Instrument] Order By [SerialNo]"
rs.Open sql, conn, adOpenForwardOnly
loader = 0
rs.MoveFirst
Do While Not rs.EOF
sn = CStr(rs![SerialNo])
InstrumentIDs(loader) = sn
loader = loader + 1
rs.MoveNext
Loop
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Exit Sub
GetInstrumentError:
MsgBox "Error loading instruments: " & Err.Description
End Sub
You must set a reference to Microsoft ActiveX Data Objects m.n Library (latest version on my computer is 2.8) from Tools > References in VBA editor.
See article
http://www.thespreadsheetguru.com/blog/2014/5/14/vba-for-excels-form-control-combo-boxes for tips on how to manage dropdown boxes in Excel.
You can use the MS Query Wizard in Excel to store a query and use it's data any time.
This this link for details http://www.techrepublic.com/article/use-excels-ms-query-wizard-to-query-access-databases/