Set MS-Access Image Control Source from Attached Image Using VBA - vba

I'm adding a photo to form to display for each user with other info of that user. I created a tabbed form, on page one I select a user and press a button that runs the following code:
Private Sub Command106_Click()
Dim qry_rs As DAO.Recordset
Dim qry_db As Database
Set qry_db = CurrentDb
SQLString = "SELECT [Clients Info].* FROM [Clients Info] WHERE ((([Clients Info].Info_Client)='" & [Forms]![Form-1]![Combo13_PageOne_Name] & "'));"
Set qry_rs = qry_db.OpenRecordset(SQLString)
Forms![Form-1].[Info_Member].Value = qry_rs![Info_Member]
Forms![Form-1].[Info_Tower].Value = qry_rs![Info_ID]
End Sub
I tried using the same way that I set the values of that textboxes in setting an image control value
Forms![Form-1].[Info_Picture].Value = qry_rs![Info_UserIDPhoto]
But it's not working, can anyone help?
I receive this message:
Run time error 2465:
Microsoft Office Access can't find the field "|" referred to in your expression
I'm using Office 2007, on Windows 7

To my knowledge, there is no way to refer to the ControlSource property through vba. However, using the property sheet in Design View works PERFECTLY. Use the value of your combo box as the criteria in a DLookup expression.
Enter this as the ControlSource of your image control:
=DLookUp("[YourAttachmentField]","[YourTable]","[YourNameField] = '" & [YourComboBox]. [Column] (x) & "'")
(Make sure you're referencing the correct column; I'm just using x as an example.)
This won't work if you alter the attachment's name or location AFTER it's been attached, so if any changes are made you must reattach.

VBA allows you to set the Picture property:
Forms![Form-1].[Info_Picture].Picture=qry_rs![Info_UserIDPhoto]
The Picture property value must be a file name--or complete path and file name if not found in the default folder set in Access options.
When set from VBA, the value may be a statement or variable whose value is a (path and) file name. In the case above, the field [Info_UserIDPhoto] would contain the complete path and file name of each user's ID photo.
(Unlike the ControlSource property, you cannot enter a variable or field name for this property directly in the design view property page.)

You can reference the control source property by doing the following:
Dim c As Control
Set c = Forms("FormName").Form.Controls("ControlName")
c.Properties("ControlSource") = "Your control source name here"

Related

Execute MySQL Select passthrough from a subform and send output recordset to a parent form

I manage a Microsoft Access 2019 Database (owned by a customer) with a form (named Mainform) whose recordset source is a MySQL passthrough query (SELECT * FROM table_on_mysql_db); each recordset (shown directly on opening Mainform) is only readable and it has three fields: one of them, description, contains text.
On double clicking on description field, a small sized subform (name Subform, containing one textvalue field named keywordDescr, plus an OK button and a Cancel button) pops up.
If I enter some words in keywordDescr (i.e. anyword) and press OK, the following passthrough query
SELECT * FROM table_on_mysql_db WHERE description LIKE '%anyword%'
is being called and the resultset ouput must be displayed in Mainform (Subform still remains opened); unfortunately, the Mainform content is not updated accordingly to the above MySQL filtered query.
The following is the VBA code called on clicking the OK button in Subform (OK is the label and the button name is button_search_description):
Private sub button_search_description_Click()
on Error goto ErrDescr
Dim qdfc as DAO.QueryDef
Dim qryPT as String
Dim ODBC_STRING as String
Dim kwd as String
kwd = Me.keywordDescr
kwd = Replace(kwd, "*", "%") '(the customer is still used to entering Access wildcard rather than MySQL wildcard!)
kwd = Replace(kwd, "'", "\'")
ODBC_STRING = "ODBC;DSN=MY_DSN_NAME" ' it works!
qryPT = "SELECT * FROM table_on_mysql_db WHERE description LIKE '" & kwd & "'"
DoCmd.setWarnings = false
Set qdfc = DBEngine(0)(0).CreateQueryDef("")
With qdfc
.Connect = ODBC_STRING
.SQL = qryPT
.ReturnsRecords = True
Me.Parent.RecordSource = qryPT
End With
Set qdfc = nothing
DoCmd.setWarnings = true
ErrDescr:
Resume Next
End Sub
Really doesn't make sense to modify query object and then set form RecordSource to that same SQL statement.
In design view, set form RecordSource to pass-through query object name or an SQL statement that uses pass-through query as source: SELECT * FROM PTQname;. Use code to modify pass-through query object to change parameters but don't change form RecordSource.
Finally, I solved the problem; #deluxeinformation gave me the right track, but I also wish to thank tho other users who gave me useful hints.
I defined a view on MySQL database named View_list, then set View_list as Mainform record source and, on Mainform load, the filtered PT query SELECT * FROM View_list WHERE F1 is executed, where F1 is the default filter where Mainform is loaded.
Similar PT query but with a different filter is being called clicking on the OK button in the Subform; the VBA code bound to this event is the following (kwd is the value entered in the input text keywordDescr of the subform Subform):
qryPT = "SELECT * FROM View_list WHERE description LIKE '" & kwd & "'"
With qdfc
.Connect = ODBC_STRING
.SQL = qryPT
.ReturnsRecords = True
Forms!Mainform.RecordSource = qryPT
End With
It's a little confusing to me what you're trying to do here but as I understand it you have a pure MySQL query (PTQName) that is the recordsource of a form (MainForm) when it is first opened. Right now this is a passthrough query defined in Access but not in MySQL. Then you want to be able to open a pop up form to filter the results you get from PTQName in MainForm. What I would do first is take the code for PTQName and create an actual view in MySQL Workbench from this (for example, call it "MyView"). Then link that view into your Access database. Access will treat this MySQL view as just another linked table. Set the recordsource of your MainForm to the name of this view so when it opens it displays records from your view. When you want to filter the records shown in your MainForm using your popup form, either use MainForm's Filter and FilterOn properties, or set MainForm's recordsource = "select * from MyView where ...". I am not seeing a need to even use a pass-through query here, let alone modify its SQL at runtime. But if I am misunderstanding please let me know!

How do I populate the destination of a report export based on the value of a text box

I currently have the following VBA code running:
DoCmd.OutputTo acReport, "r_GRV_DETAIL_EXPORT", "MS-DOSText(*.txt)", "C:\Application\TSClient\Bin1\Scans\123.txt", False, ""
However, I will have different users using the application and they each have a specific location where they would need to export the report to (bin2, bin3 etc). I am going to have them select the user name and based on that the export location will be populated in a text book.
Question: How do I go about populating the above code with the location as defined in the text box (call it: txt_MAIN_SCAN_LOCATION).
Any help will be greatly appreciated.
Please try the next approach:
Dim strSpecif as String
strSpecif = Forms![frm_MAIN_MENU]![txt_MAIN_SCAN_LOCATION].Value
Then, use this new variable in your code:
DoCmd.OutputTo acReport, "r_GRV_DETAIL_EXPORT", "MS-DOSText(*.txt)", strSpecif , False, ""
Using of the Value property will not make necessary the previous SetFocus on the text box, like in case of Text property.

Making QRCode ActiveX Control for MS Access: Control Source Property

I wanted to implement a QR Code to Access2010 and I found https://github.com/yas78/QRCodeLibVBA. Referencing XLAM from Access did not work and I didn't want to insert all modules directly to Access as it makes the project messy.
So I decided to create an OCX file using ancient VB6 as it seemed to be the easiest way to encapsulate all the bits together into one simple object.
Finally, I have made an OCX that has several key properties: DataString which is the string to be displayed, ByteModeCharsetName, ErrorCorrectionLevel, ForeRGB and BackRGB, there are also methods Refresh, Cls and events OnClick and OnDblClick
It works fine in VB6 apps + Excel sheets + Excel forms but it behaves weird in Access forms, reports, etc.
Everything looks as one would expect in Excel:
This is how it looks in Access:
The custom properties are visible on the tab "Other" but they are not offered in VBA editor at all! However it does compile when entered manually.
Resizing control behaves weird
Control's Events like OnClick are not displayed at tab Event of Property Sheet
Here are my questions:
Are the Controls for Access "different" than for other office apps?
Why the hell are the properties hidden in editor?
How to "move" some properties to other tabs (categories), for example ForeRGB to tab Format (as usual for TextBoxes etc.)?
How to create ControlSource propety (on the DATA tab) which could be directly bound to a recordset without having to use a VBA? This way, I hope, I could use the control on the continuous forms as well. In fact, this is most important question.
Some tips for resizing? (not important)
I think I'm pretty close to my goal but I'm stuck at this point. I know the VB6 is obsolete but after reading Creating Custom Controls for ms access 2010 VB6 seems to be easy choice. Any alternatives for writing OCX?
EDIT: Final working control is available here https://github.com/Combinatix/QRCodeAX
For 4. try setting your control's DataBindingBehavior to vbSimpleBound so that a scalar property (ControlSource in your case) can be bound via DataSource and DataMember properties.
For 3. use Tools->Procedure Attributes... menu, select ControlSource in Name, expand Advanced>> and select Data in Property Category combobox. You can do the same through Object Browser (F2). Find your control, right click your property/method (should be bold) and choose Properties... context menu option. This works with methods and is more versatile than Tools->Procedure Attributes... approach.
To answer your questions one by one:
Yes. ActiveX controls in Access are certainly different than in other Office applications.
In Access, there's one general CustomControl control that encapsulates all ActiveX controls, and offers a default set of events, properties and methods for any control, such as border properties, the requery method, and the enter event.
The object of the control being encapsulated can be accessed by using the CustomControl.Object proprty
These properties aren't displayed because you're referring to a custom control in the general sense, and only get the properties for it.
To get the object you want, use the following:
Dim qrObj As QRCode
Set qrObj = QR.Object
That's plain not possible, tab layout is determined by Access
Also not possible. The ActiveX control must include that functionality, this one doesn't. Generally, using ActiveX controls in continuous subforms to display something different for every row is hard to impossible
Resizing the outer control, and then calling CustomControl.SizeToFit should generally just work
Some of the things I deem not possible can be achieved by modifying the ActiveX Control's source code, of course.
A very different and much less cumbersome approach would be to generate the QR code online and download them to be displayed in a (bound) picture control.
I wrote an article on displaying online images:
Show pictures directly from URLs in Access forms and reports
Some code is, of course, needed, but much less than that at GiHub you refer to, though to much to list here in full.
It uses this function retrieve the images:
' Download (picture) file from a URL of a hyperlink field to a
' (temporary) folder, and return the full path to the downloaded file.
'
' This can be used as the control source for a bound picture control.
' If no Folder is specified, the user's IE cache folder is used.
'
' Typical usage in the RecordSource for a form or report where Id is
' the unique ID and Url is the hyperlink field holding the URL to
' the picture file to be displayed:
'
' - to a cached file where parameter Id is not used:
'
' Select *, UrlContent(0, [Url]) As Path From SomeTable;
'
' - or, where Id is used to create the local file name:
'
' Select *, UrlContent([Id], [Url], "d:\somefolder") As Path From SomeTable;
'
' Then, set ControlSource of the bound picture control to: Path
'
' 2017-05-28. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function UrlContent( _
ByVal Id As Long, _
ByVal Url As String, _
Optional ByVal Folder As String) _
As Variant
Const NoError As Long = 0
Const Dot As String = "."
Const BackSlash As String = "\"
Dim Address As String
Dim Ext As String
Dim Path As String
Dim Result As String
' Strip leading and trailing octothorpes from URL string.
Address = HyperlinkPart(Url, acAddress)
' If Address is a zero-length string, Url was not wrapped in octothorpes.
If Address = "" Then
' Use Url as is.
Address = Url
End If
If Folder = "" Then
' Import to IE cache.
Result = DownloadCacheFile(Address)
Else
If Right(Folder, 1) <> BackSlash Then
' Append a backslash.
Folder = Folder & BackSlash
End If
' Retrieve extension of file name.
Ext = StrReverse(Split(StrReverse(Address), Dot)(0))
' Build full path for downloaded file.
Path = Folder & CStr(Id) & Dot & Ext
If DownloadFile(Address, Path) = NoError Then
Result = Path
End If
End If
UrlContent = Result
End Function
I pasted this URL into a record:
https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=23457
and it worked right away:
Full code can be found at GitHub: VBA.PictureUrl

Save file with name from form content

I'm trying to save a Microsoft Word 2013 document with a specific filename.
I created a Word form that a client fills out.
I am using the following: DEVELOPER -> Controls -> Plain Text Content Control DEVELOPER -> Controls -> Date Picker Content Control DEVELOPER -> Controls -> Drop-Down List Content Control
I would like a macro to save the document with the name of one of the fields in the form.
Example:
below are fillable content fields.
client reference: A1B2-345
date: August 17, 2015
type: metadata
I would like to save the file as:
A1B2-345_17082015_metadata.DOCX
Start by giving each of your controls a Title. You can do this by clicking on your control in your document and then click Properties on the Developer ribbon. The first field on the Properties window is Title. Give each one of the controls you need to access a unique title. In the example below, I'm using MyText, MyDate, and MyDrop for the text, date, and drop-down controls, respectively.
Then you can access each control in VBA by using the SelectContentControlsByTitle() function. As long as you're using a unique title, this function will return a collection containing only a single control so we can just retrieve the first item from the collection (index (1)). Here's how this would look:
Dim strText As String, strDate As String, strDrop As String
strText = ThisDocument.SelectContentControlsByTitle("MyText")(1).Range.Text
strDate = ThisDocument.SelectContentControlsByTitle("MyDate")(1).Range.Text
strDrop = ThisDocument.SelectContentControlsByTitle("MyDrop")(1).Range.Text
The Range.Text ending is what grabs the current text/value from the control.
Now that you have your three pieces of information, you can concatenate them into one string using the concatenation operator (&):
Dim strFilename As String
strFilename = strText & "_" & Format(strDate, "ddmmyyyy") & "_" & strDrop & ".docx"
And, finally, save it:
ThisDocument.SaveAs strFilename
It should be noted that the code provided above will not work properly if you are generating the form based off a template (.dotm). The following lines that include the ThisDocument.SelectContentControlsByTitle need to be changed to
ActiveDocument.SelectContentControlsByTitle otherwise the code will pull the place holder text from the content control.

Microsoft Access- launch hyperlink contained in data table via button located on form

Using SQL or VBA, what is the code I would need to launch a hyperlink which would go to either the internet or a network location? The form has multiple buttons which would connect 1:1 with the first column in the table. The second column in the table would either have an "http://www.internet.com/databases" or "\network7\HH\forms\hrl\".
Only the admin would have access to the table, and the end-users only have access to the forms. This allows all the users to click on the button and have the website or network location launch automatically, without having the ability to edit the table, which the admin would have.
Within "OnClick", I cannot simply type "FollowHyperlink(http://www._____) because the location (written in the table) would be changing monthly and the admin would have 0 coding or technical background.
The button would not be opening a table or showing the user what is happening, it would only launch the link and remain on the same screen to allow them to click on another button
Thank you in advance,
JT
so far i have:
Dim hyperlink As String
hyperlink = Nz((DLookup("Field2", "sources", "[Field1] = SAP"),"")
If Len(hyperlink) > 0 then
FollowHyperlink (hyperlink)
End If
You have to get the data out of the table and then open it as a hyperlink. so something like this:
Dim rs as recordset
Dim hyperlink as string
set rs = currentdb.openrecordset("Table")
rs.movefirst
hyperlink = rs![RelevantColumn]
rs.close
set rs = nothing
FollowHyperlink(hyperlink)
-----------------------------------EDIT
We found the final solution in the comments:
Private Sub Criteria_Click()
anything3 = DLookup("TargetField", "sources", "[CriteriaField] = 'Criteria'")
FollowHyperlink anything3
End Sub