Access vba display local PDF file using web browser control - ms-access

In ms access 2013, I have a user form (frm_viewer) containing a web browser control named wbContent.
I wrote the following code to populate and display a local PDF file but cannot seem to get it to function correctly.
I did manage to get it working by referencing the Control Source property of the control to a textbox on the same form (i.e. Control Source -> Base URL -> Expression Builder -> =[MyTextbox]) but I do not want to use this method, I prefer to populate it on the fly using variables.
Private Sub lblBrowse_Click()
'declare file dialog with late binding ->
Dim fDialog As Object, strPath As String
Set fDialog = Application.FileDialog(3) 'msoFilePicker
'set parameters ->
Me.wbContent.ControlSource = ""
'initializing the file dialog ->
With fDialog
.AllowMultiSelect = False
.Filters.Clear '
.title = "Please select a file..."
'display the dialog box. If the .Show method returns True
'the user picked a file. If the .Show method returns False
'the user clicked Cancel.
If .show = True Then
strPath = .SelectedItems(1)
Debug.Print "SELECTED_FILE: " & strPath
'set source property to the string containing the full path ->
Me.wbContent.ControlSource = strPath
Me.wbContent.Requery
Else
End If
End With
End Sub
Could someone please take a look at my code and let me know how I can get it to function correctly?
Thanks!

Try this:
Me.wbContent.ControlSource = "='" & strPath & "'"
The control source needs to be a string like so: ='http://www.address.com'

Related

Adding Filename to a column with your textfile Import

I have built a form where a user can select one or more files and import them into a single table. When the user selects the file, or yet, multiple files, once the import is complete, I want the file name to be added on each row, of course, related to the correct file.
I am able to setup a query to manually add the filename, but how would I be able to do this in a more automated fashion. For example, if the user selects a file how can I code the SQL query to automatically detect the filename and add it? If the user selects more than one file, how can the query write the correct filename for each row?
Here is my form code:
Option Compare Database
'Private Sub Command0_Click()
Private Sub cmdFileDialog_Click()
'Requires reference to Microsoft Office 12.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
'Clear listbox contents.
'Me.FileList.RowSource = ""
'Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Allow user to make multiple selections in dialog box.
.AllowMultiSelect = True
'Set the title of the dialog box.
.Title = "Please select one or more files"
.InitialFileName = "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC"
'Clear out the current filters, and add our own.
.Filters.Clear
'.Filters.Add "Access Databases", "*.MDB; *.ACCDB"
.Filters.Add "Access Projects", "*.txt"
'.Filters.Add "All Files", "*.*"
'Show the dialog box. If the .Show method returns True, the
'user picked at least one file. If the .Show method returns
'False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to the list box.
For Each varFile In .SelectedItems
' Me.FileList.AddItem varFile
Call InsertCMS_Reports_2ndSave(varFile)
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
Module Code:
Function InsertCMS_Reports_2ndSave(FileName As Variant)
'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave"
DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _
"CMS_Reports_Import", "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC\FileName"
CurrentDb.Execute "UPDATE CopyOfCOMPRPT_CE SET FileName = 'HLTH_COMPRPT_1701011028174_h0062.txt' WHERE FileName is NULL", dbFailOnError
End Function
Provided the code you provided is already working, then this should work for you.
CurrentDb.Execute "UPDATE CopyOfCOMPRPT_CE SET FileName = '" & FileName & "' WHERE FileName is NULL", dbFailOnError
If you have issues, it's most likely a syntax issue with the sql string and quotation marks will be the most likely culprit. If you have problems, put a debug statement in your code so you can see what sql statement is getting generated. For instance:
Function InsertCMS_Reports_2ndSave(FileName As Variant)
Dim strSQL as String
'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave"
DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _
"CMS_Reports_Import", "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC\FileName"
strSQL = "UPDATE CopyOfCOMPRPT_CE SET FileName = '" & FileName & "' WHERE FileName is NULL", dbFailOnError"
debug.print strSQL
CurrentDb.Execute strSQL, dbFailOnError
End Function

Creating a button in Access to to open a word document

I have a word document that uses mail merge feature and gets its information from the access db. When I use this code it does not open the word document with the current information. It opens the word document with the last saved information.
If I open the word document on its own, from the task bar, it asks if I want to run the SQL and I click yes and everything operates normally. I want to click a button from within access to accomplish this same task to open the contract.
Here is the code I used:
Private Sub Command205_Click()
Dim LWordDoc As String
Dim oApp As Object
'Path to the word document
LWordDoc = "C:\Users\.....k Up\01- Proposal\contract.docx"
If Dir(LWordDoc) = "" Then
MsgBox "Document not found."
Else
'Create an instance of MS Word
Set oApp = CreateObject(Class:="Word.Application")
oApp.Visible = True
'Open the Document
oApp.Documents.Open FileName:=LWordDoc
End If
End Sub
***I should add that I am not a coder and know nothing about VBA, I copied this from this website so any help you can offer would be greatly appreciated. If you can provide me with coding or enough guidance to get me on the way would be great. Thank you
This code will run in Access to open a Mail Merge document and update content and save.
Using the link I originally posted (http://www.minnesotaithub.com/2015/11/automatic-mail-merge-with-vba-and-access/), I made a couple of modifications and was able to get that code to work.
I needed to add: ReadOnly:=True, _ to prevent a sharing violation
and I changed the Table Name of the source data.
NOTE!! You will need to change sode marked with'###' as follows:
###-1 Change to specify the full path of your TEMPLATE!!!
###-2 Change the SQLSTATEMENT to specify your recordsource!!!
Paste this code into your form, make sure you have a Command Button Click Event that executes (Either rename 'Command205' in this code, or change your control name).
Option Compare Database
Option Explicit
Private Sub Command205_Click()
Dim strWordDoc As String
'Path to the word document of the Mail Merge
'###-1 CHANGE THE FOLLOWING LINE TO POINT TO YOUR DOCUMENT!!
strWordDoc = "C:\Users\.....k Up\01- Proposal\contract.docx"
' Call the code to merge the latest info
startMerge strWordDoc
End Sub
'----------------------------------------------------
' Auto Mail Merge With VBA and Access (Early Binding)
'----------------------------------------------------
' NOTE: To use this code, you must reference
' The Microsoft Word 14.0 (or current version)
' Object Library by clicking menu Tools > References
' Check the box for:
' Microsoft Word 14.0 Object Library in Word 2010
' Microsoft Word 15.0 Object Library in Word 2013
' Click OK
'----------------------------------------------------
Function startMerge(strDocPath As String)
Dim oWord As Word.Application
Dim oWdoc As Word.Document
Dim wdInputName As String
Dim wdOutputName As String
Dim outFileName As String
' Set Template Path
wdInputName = strDocPath ' was CurrentProject.Path & "\mail_merge.docx"
' Create unique save filename with minutes and seconds to prevent overwrite
outFileName = "MailMergeFile_" & Format(Now(), "yyyymmddmms")
' Output File Path w/outFileName
wdOutputName = CurrentProject.Path & "\" & outFileName
Set oWord = New Word.Application
Set oWdoc = oWord.Documents.Open(wdInputName)
' Start mail merge
'###-2 CHANGE THE SQLSTATEMENT AS NEEDED
With oWdoc.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:=CurrentProject.FullName, _
ReadOnly:=True, _
AddToRecentFiles:=False, _
LinkToSource:=True, _
Connection:="QUERY mailmerge", _
SQLStatement:="SELECT * FROM [tblEmployee]" ' Change the table name or your query
.Destination = wdSendToNewDocument
.Execute Pause:=False
End With
' Hide Word During Merge
oWord.Visible = False
' Save file as PDF
' Uncomment the line below and comment out
' the line below "Save file as Word Document"
'------------------------------------------------
'oWord.ActiveDocument.SaveAs2 wdOutputName & ".pdf", 17
' Save file as Word Document
' ###-3 IF YOU DON'T WANT TO SAVE AS A NEW NAME, COMMENT OUT NEXT LINE
oWord.ActiveDocument.SaveAs2 wdOutputName & ".docx", 16
' SHOW THE DOCUMENT
oWord.Visible = True
' Close the template file
If oWord.Documents(1).FullName = strDocPath Then
oWord.Documents(1).Close savechanges:=False
ElseIf oWord.Documents(2).FullName = strDocPath Then
oWord.Documents(2).Close savechanges:=False
Else
MsgBox "Well, this should never happen! Only expected two documents to be open"
End If
' Quit Word to Save Memory
'oWord.Quit savechanges:=False
' Clean up memory
'------------------------------------------------
Set oWord = Nothing
Set oWdoc = Nothing
End Function

How to use filedialogbox to save filepath in string, using Access VBA?

I have an Access file which I will be using for quality assurance of data.
I will be inputting data from three Excel files, each into its own Access table.
At present, I have three buttons and corresponding text boxes. I manually enter the file path and name into the text box, click the button and it completes the rest of my macro, importing the data.
I'd like to use the file picker dialog box to populate the textbox with the path.
This code and worked for me:
Private Sub Comando32_Click()
Dim f As Object
Dim strFile As String
Dim strFolder As String
Dim varItem As Variant
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For Each varItem In f.SelectedItems
strFile = Dir(varItem)
strFolder = Left(varItem, Len(varItem) - Len(strFile))
MsgBox "Folder: " & strFolder & vbCrLf & _
"File: " & strFile
Me.certidao.Value = varItem
Next
End If
Set f = Nothing
End Sub
Of course, it is possible to call the file Dialog API in VBA!
An example direct from Microsoft VBA documentation:
Private Sub cmdFileDialog_Click()
' Requires reference to Microsoft Office XY.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
' Clear listbox contents.
Me.FileList.RowSource = ""
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
' Allow user to make multiple selections in dialog box
.AllowMultiSelect = True
' Set the title of the dialog box.
.Title = "Please select one or more files"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Access Databases", "*.MDB"
.Filters.Add "Access Projects", "*.ADP"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to our list box.
For Each varFile In .SelectedItems
Me.FileList.AddItem varFile
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
Please note you have to include a reference to Microsoft Office 11.0 Library
(in code window, select menu option Tools, Reference and select your library for the correct version of your Office Version)
Thanks for the response.
I did google it first and tried everything I came across. I also came across the very set of code pasted above. I Played around with it for a while and whatever I did returned errors. I decided to try the code in Excel instead of Access and it worked straight away. The only thing I could think was that the code wasn't applicable to access. Following all of that I asked the question here.
Private Sub cmdDialog_Click()
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Me.txtFileSelect.RowSource = ""
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Please select one or more files"
.Filters.Clear
.Filters.Add "Excel Files", "*.XLSX"
.Filters.Add "All Files", "*.*"
If .Show = True Then
For Each varFile In .SelectedItems
Me.txtFileSelect.AddItem varFile
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
With this code I get:
Compile error;
User-defined type not identified
Try this code, for single file:
MyFileURL = aBrowseForFile("C:\users\")
Public Function aBrowseForFile(aStartFolder As String) As String
' Needs a reference to Microsoft Office Object Library 15.0
On Error GoTo Err_txtBrowseForFile
Dim fDialog As Office.FileDialog
Dim varfile As Variant
Dim strPath As String
Dim strFilter As String, strFileName As String
Dim Main_Dir As String, DefFolder As String
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.InitialView = msoFileDialogViewThumbnail
.AllowMultiSelect = False
.Title = "Please select one or more files"
.InitialFileName = aStartFolder
.InitialView = msoFileDialogViewThumbnail
.Filters.Clear
.Filters.Add "all files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
aBrowseForFile = .SelectedItems(1)
Else
'MsgBox "You clicked Cancel in the file dialog box."
End If
End With
Exit_txtBrowseForFile:
Exit Function
Err_txtBrowseForFile:
MsgBox Err.Description, vbCritical, "MyApp"
Resume Exit_txtBrowseForFile
End Function
Put this function in a module, as it is.
Do not put some other code inside, so you can call it in other projects and build your own tools set.
Call it as shown above in your form.
This code runs well and it is tested.
If you want to check this code, in the debug window type
debug.print aBrowseForFile("C:\users\")
and see what happens. If you have other run-time or compile errors, please post another question.
Hope this helps
Thanks for the response.
I solved the problem in the end, I hadn't selected the object database. I found the following code to work:
Private Sub cmdInput_Click()
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Please select a file"
.Filters.Clear
.Filters.Add "Excel Files", "*.XLSX"
.Filters.Add "All Files", "*.*"
If .Show = True Then
For Each varFile In .SelectedItems
DoCmd.TransferSpreadsheet acImport, 10, "InputData", varFile, True, ""
Beep
MsgBox "Import Complete!", vbExclamation, ""
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub

storing large numbers of images in ms access

I have a inventory/Contact database where I need to store a lot of images (10k items, 1k people). Now, obviously ole object is out of the question due to the sheer bloat.
Is there a better way to do this, such as storing the pathway to the image ( would be stored in a folder with the database) and having that image displayed where I need it(this would be great because some items are repeated)? Is there anyway to do this? (also, i really need to have a filebrowser to the actual image instead of typing the path manually (that would be hell))
Here is a concept
Sub Locate_File()
Dim fDialog As Office.FileDialog
Dim file_path As String
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Set the title of the dialog box.
.Title = "Please select one or more files"
'Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "All Files", "*.*"
'Show the dialog box. If the .Show method returns True, the
'user picked at least one file. If the .Show method returns
'False, the user clicked Cancel.
If .Show = True Then
file_path = .SelectedItems(1)
Copy_file(file_path,Right(file_path, Len(file_path) - InStrRev(file_path, "\")))
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End
Sub Copy_file(old_path As String, file_name As String)
Dim fs As Object
Dim images_path As String
images_path = CurrentProject.Path & "\images\"
Set fs = CreateObject("Scripting.FileSystemObject")
fs.CopyFile old_path, images_path & file_name
Set fs = Nothing
'Update your database with the file location of images_path & file_name
End
You may need to make changes and you must require the Microsoft Office 12.0 Object Library for FileDialog to work. Much of the FileDialog code was taken from Microsoft

Import MS Word form fields into MS Access

I have created an application form using MS Word and a whole bunch of form fields, and I have an Access db that can import all the data I need from this Word doc, thanks to this:
http://msdn.microsoft.com/en-us/library/aa155434%28office.10%29.aspx
Now everything works just fine (I even managed to get it to import into multiple tables!), but the problem with the above is that I have to manually enter the name of each file one at a time... which is fine if it's just a case of importing the application form as it comes in... but I have quite a lot sitting in a folder that needs entered into the database.
Then I found this:
How to show "Open File" Dialog in Access 2007 VBA?
I've tried to tweak and merge the two to make it work... but as you can guess, to no avail... (it doesn't help when I'm very much an Access novice!)
What I am looking to do is to be able to import a bunch of Word docs / form fields into MS Access by using the Open / Select file dialogue box... what I've got works, but I'd like to make it easier to work with!
Thanks everyone
Jake
##### Codes I been using
Option Compare Database
Option Explicit
Private Sub cmdFileDialog_Click()
' This requires a reference to the Microsoft Office 11.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Dim appWord As Word.Application
Dim doc As Word.Document
' Dim cnn As New ADODB.Connection
' Dim rst As New ADODB.Recordset
Dim strDocName As String
Dim blnQuitWord As Boolean
' Clear the list box contents.
' Me.FileList.RowSource = ""
' Set up the File dialog box.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
' Allow the user to make multiple selections in the dialog box.
.AllowMultiSelect = True
' Set the title of the dialog box.
.Title = "Select One or More Files"
' Clear out the current filters, and then add your own.
.Filters.Clear
.Filters.Add "Microsoft Word", "*.DOC"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
' Loop through each file that is selected and then add it to the list box.
For Each varFile In .SelectedItems
' Me.FileList.AddItem varFile
Set appWord = GetObject(, "Word.Application")
Set doc = appWord.Documents.Open(varFile)
' cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
' "Data Source=M:\Medical\GPAppraisal\Contacts & Databases\" & _
' "AppForm.mdb;"
' rst.Open "tbl_Applicants", cnn, _
' adOpenKeyset, adLockOptimistic
' With rst
.addnew
!Title = doc.FormFields("wTitle").Result
!FirstName = doc.FormFields("wFirstName").Result
!LastName = doc.FormFields("wLastName").Result
!Address1 = doc.FormFields("wAddress1").Result
!Address2 = doc.FormFields("wAddress2").Result
!Address3 = doc.FormFields("wAddress3").Result
!City = doc.FormFields("wCity").Result
!PostCode = doc.FormFields("wPostCode").Result
!Email = doc.FormFields("wEmail").Result
!Phone1 = doc.FormFields("wPhone1").Result
!Phone2 = doc.FormFields("wPhone2").Result
!LM = doc.FormFields("wLM").Result
!LMAddress1 = doc.FormFields("wLMAddress1").Result
!LMAddress2 = doc.FormFields("wLMAddress2").Result
!LMAddress3 = doc.FormFields("wLMAddress3").Result
!LMCity = doc.FormFields("wLMCity").Result
!LMPostCode = doc.FormFields("wLMPostCode").Result
!LMEmail = doc.FormFields("wLMEmail").Result
!LMPhone = doc.FormFields("wLMPhone").Result
!LMOK = doc.FormFields("wLMOK").Result
!Probity = doc.FormFields("wProbity").Result
!Practising = doc.FormFields("wPractising").Result
!Signature = doc.FormFields("wSignature").Result
!AppDate = doc.FormFields("wAppDate").Result
!e2011012028 = doc.FormFields("w2011012028").Result
!e2011021725 = doc.FormFields("w2011021725").Result
!e2011030311 = doc.FormFields("w2011030311").Result
!e2011031625 = doc.FormFields("w2011031625").Result
!e20110203 = doc.FormFields("w20110203").Result
!e20110211 = doc.FormFields("w20110211").Result
!e20110322 = doc.FormFields("w20110322").Result
!e20110330 = doc.FormFields("w20110330").Result
.Update
.Close
End With
doc.Close
If blnQuitWord Then appWord.Quit
cnn.Close
MsgBox "Application Imported!"
Cleanup:
' Set rst = Nothing
' Set cnn = Nothing
Set doc = Nothing
Set appWord = Nothing
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
#
I've tried to mess with me.tables and me!forms and .add etc etc - obviously I'm a complete novice here!!!
What I want is to be able to import data from form fields in a Word Doc into a MS Access table (which I have managed to do with the first URL in my original post above); by means of selecting the Word doc from the Open/Select dialogue box, instead of manually entering the names of each Word doc.
My apologies if it sounds obvious or simple - Access is not my strong point by any means!
Before I begin I didn't understand why you have so many uncommented lines (lines beginnig mit ' ) in you code example. I assume that most of those lines would normally not bei uncommented and be part of the working code. Or are there artifacts of the Stack Overflow Editor?
I see a few problems, that might to guide you to a solution.
1) When you use
With fDialog
you let this 'open' until the end of the code (even using a second With in between). I would recommend to set you corresponding 'End With' right after you no longer require it. Remeber (or take note): The
With fDialog
[... something]
' Set the title of the dialog box.
.Title = "Select One or More Files"
is really just a shorthand for
fDialog.Title
(i.e. a "naked" . means, that it has to be appendend to the object in the With) so you could do away with the "With" entirely. IN you example I would set the "End With" right before
If .Show = True Then
and then use
If fDialog.Show = True Then
2) I would set
Set appWord = GetObject(, "Word.Application")
outside your For Each loop (don't forget to take Set appWord = Nothing outside the loop as well). Remember that with GetObject you need an runnig Word-instance, otherwise you might want to use
Set appWord = CreateObject("Word.Application")
or to have it both ways, try to get a Word-object, and if it is not available (i.e. Err.Number = 429) create a new one.
On Error Resume Next
Set appWord = GetObject(, "Word.Application")
If Err.Number = 429 Then
Set appWord = CreateObject("Word.Application")
End If
On Error GoTo 0
3) When working or at least while developping using automation I would always set
objword.Visible = True
so you see error messages or other problems right within Word.
HTH for the next steps (in case you have this problem anymore)
Andreas