VBA MS Access 2007 hyperlink insert button - vba

I have a button which inserts a hyperlink into a new record. The field's IsHyperlink property is set to "yes", so I get the hand, but clicking on the inserted path does not go anywhere. I believe the button is updating the record with the path of the file as "text to display" rather than "address."
Private Sub MSDS_btn_Click()
Dim fd As Office.FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Use a With...End With block to reference the FileDialog object.
With fd
'Set the initial path to the D:\Documents\ folder.
.InitialFileName = "D:\Documents\"
.Title = "Select MSDS"
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the action button...
If .Show = -1 Then
DoCmd.GoToRecord , "", acNewRec
Me![Link MSDS] = .SelectedItems(1)
**
'If the user presses Cancel...
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
I know that putting the following code in at the ** works in Excel, I am after something like it which will work in Access!
ActiveSheet.Hyperlinks.Add Anchor:=Cells(ActiveCell.row, Range("LinkCol").Column), Address:=.SelectedItems(1), TextToDisplay:="MSDS"

Try this if you want the file path as both the hyperlink address and display text.
Me![Link MSDS] = "#" & .SelectedItems(1) & "#"
If you want the address with only the file name (without the path) as the display text, try this:
Me![Link MSDS] = Dir(.SelectedItems(1)) & "#" & .SelectedItems(1) & "#"
See HyperlinkPart Method for more background information. You might even prefer to manipulate your hyperlink field data using HyperlinkPart.

Related

Copying image in Word VBA

I have an image control in a Word UserForm and a button which opens a dialog box to let the user select an image. If I want to copy this image to another document, how do I do it via code?
Here's the code to select the image via the button:
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Select Photo"
.Filters.Clear
.Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1
If .Show = -1 Then
filetoinsert = .SelectedItems(1)
For Each vrtSelectedItem In .SelectedItems
Next vrtSelectedItem
Me.myImage.Picture = LoadPicture(.SelectedItems(1))
Else
End If
End With
Set fd = Nothing
End Sub
At the bottom of this form, I have another button that will copy this photo to another document. Here's what i've tried so far:
Private Sub cmdTransferPhoto_Click()
'Copy and Paste photo on "NextDoc" document. On the this document, I have a Picture Content Control called "Picture" where i plan to paste the copied image
Set Picture = NextDoc.SelectContentControlsByTitle("Picture").Item(1)
Picture.Range.InlineShapes.AddPicture _
Me.myImage.Picture, linktofile:=False, savewithdocument:=True
End Sub
When I click, the cmdTransferPhoto button, I get this error
Run-time error '5152'
This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was type correctly.
*Select a file from the list of files and folders.
Ideas are welcome! Thanks.
As you could have discovered from the documentation, and should have noticed from the Intellisense, .InlineShapes.AddPicture takes FileName, datatype string, as the required argument. As you are attempting to pass an image (which will be a rather poor quality bitmap) into this argument it quite naturally fails.
You already obtained the filename which you used to load the picture into the image control, so why not use it?
Picture.Range.InlineShapes.AddPicture FileName:=filetoinsert, LinkToFile:=False, SaveWithDocument:=True

Insert an image file in a MAC Word Userform

I am not a programmer so not sure what to do here. I would like an option of adding an image file in a Microsoft Word document userform for MAC. I had used a code earlier which works perfectly in Windows but it doesnt work for MAC and gives a 5948 error. I had added a field for the image in the userform with a button to add the image and the final submit button. The add button should allow the user to insert any size image from the local folder.
The code I was using is given below:
Dim ImagePath As String
Private Sub CMDAddImage_Click()
Dim objFileDialog As Office.FileDialog
Set objFileDialog = Application.FileDialog(MsoFileDialogType.msoFileDialogFilePicker)
With objFileDialog
.AllowMultiSelect = False
.ButtonName = "File Picker"
.Title = "File Picker"
If (.Show > 0) Then
End If
If (.SelectedItems.Count > 0) Then
Call MsgBox(.SelectedItems(1))
ImagePath = .SelectedItems(1)
End If
End With
Image1.Picture = LoadPicture(ImagePath)
End Sub
And the code in submit button was:
Dim objWord
Dim objDoc
Dim objShapes
Dim objSelection
'Set objSelection = ActiveDocument.Sections
'objSelection.TypeText (vbCrLf & "One Picture will be inserted here....")
ActiveDocument.Bookmarks("Field04").Select
Set objShapes = ActiveDocument.InlineShapes
objShapes.AddPicture (ImagePath)
End
End Sub
Can someone please help me edit the code for mac. In mac it does not allow to add the file.
You should check out the suggestion made by #JohnKorchok in a comment to your previous question - insert an image Content Control in your document instead, and throw away the VBA.
But if you need to keep using VBA and a UserForm...
Application.FileDialog is not available on Mac.
Application.GetOpenFileName is not avaialble from Word (it's an Excel thing).
Application.Dialogs does not do the same thing as GetOpenFileName so the user experience will be rather different, but at its simplest, you can use it like this:
With Application.Dialogs(wdDialogFileOpen)
' .Display = -1 for "OK" ("Open" in this case)
' .Display = 0 for "Cancel"
' (THere are other possible return values
' but I do not think they are applicable here)
If .Display = -1 Then
ImagePath = .Name
End If
End With
or if you prefer, the lengthier
Dim dlg As Word.Dialog
Set dlg = Application.Dialogs(wdDialogFileOpen)
With dlg
If .Display = -1 Then
ImagePath = .Name
End If
End With
Set dlg = Nothing
However, this dilaog does not let you specify file types or any kind of filtering, a starting folder etc. Attempts to set Finder search criteria via something like
.Name = "(_kMDItemFileName = ""*.jpg"")"
.Update
before the .Display either can't work or need different syntax.
Further, the Apple dialog may start with its
own filtering set up so the user will have to click Options to enable All Files. You don't know what file type the user will choose so you will need to deal with that.
An alternative is to invoke Applescript. For this, it appears that you can still use the VBA MacScript command, which means that you can put all the script in your VBA file. If that does not work, then unfortunately you have to use AppleScriptTask which would require you to work some more on the Script and install the script in the correct folder on every Mac where you need this feature.
Here's the code I used - you would probably need to wrap everything up in another function call and use conditional compilation or other tests to call the correct routine depending on whether the code is running on Mac or Windows
Private Sub CMDAddImage_Click()
Dim s As String
Dim sFileName As String
On Error Resume Next
s = ""
' set this to some other location as appropriate
s = s & "set thePictureFoldersPath to (path to pictures folder)" & vbNewLine
s = s & "set applescript's text item delimiters to "",""" & vbNewLine
s = s & "set theFile to ¬" & vbNewLine
' add the image file types you want here
s = s & "(choose file of type {""png"",""jpg""} ¬" & vbNewLine
s = s & "with prompt ""Choose an image to insert."" ¬" & vbNewLine
s = s & "default location alias thePictureFoldersPath ¬" & vbNewLine
s = s & "multiple selections allowed false) as string" & vbNewLine
s = s & "set applescript's text item delimiters to """"" & vbNewLine
' choose file gives as an AFS path name (with colon delimiters)
' get one Word 2016/2019 will work with
s = s & "posix path of theFile"
sFileName = MacScript(s)
If sFileName <> "" Then
' Maybe do some more validation here
ImagePath = sFileName
Image1.Picture = LoadPicture(ImagePath)
End If
End Sub

How do I pass value in textbox on form to subroutine?

I have a simple form with a few combo boxes, a textbox where the user enters the file name they want to save as (will be a spreadsheet), and a few buttons to run a few queries. When a button is pressed it opens the file dialog to select the path but the file name itself is hard coded in the subroutine. How do I take the value in the text box and pass it to the button event routine that runs the appropriate query and exports a spreadsheet? In the routine I called it fileName and the text box on the form is called FileName.
Option Compare Database
Option Explicit
Private Sub AllPaybacks_Click()
Dim getFolder As Object
Dim sLoc As String
Dim fileName As String
Set getFolder = Application.FileDialog(msoFileDialogFolderPicker)
With getFolder
.AllowMultiSelect = False
If .Show = True Then
sLoc = getFolder.SelectedItems(1) & "\"
End If
End With
DoCmd.OpenQuery "PaybackQ"
DoCmd.TransferSpreadsheet acExport, , "PaybackQ", sLoc & fileName & ".xlsx", True
End Sub
I'm a little uncertain what your exact question is.
If you want to populate the file name dialog then you can set the InitialFileName property of the getFolder object. So, inside the "with" block and before the "If" statement:
getFolder.InitialFileName = FileName.Value

Match SaveAs2 Dialog File Type To Application.FileDialog

Say you want to have a button that the user can click and save a copy of the current file as a PDF(Documentation):
Application.ActiveDocument.SaveAs2 fileName:="fileName.pdf", FileFormat:=wdFormatPDF
This works fine, the user is presented with a save dialog, selects a location and the file is saved, however a few things are not correct:
The type displayed does not match what was specified in the VBA, how can this be correct? It still saves as type "PDF" without issue, even after showing "DOCX" as the file type in the "Save as Type" drop down. Also the "fileName.pdf" is not placed in the "File Name" box, its as if the dialog box is unaware of the options set in the VBA code(This same issue is also referenced in this post).
UPDATE 1
After taking a second look at my code I now realize that the SaveAs2 Method was not displaying the dialog menu, the correct version of the code(simplified) can be described as:
Dim selected As String: selected = Application.FileDialog(msoFileDialogSaveAs).Show()
Dim filePath As String
If selected <> 0 Then
filePath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
Application.ActiveDocument.SaveAs2 fileName:=Split(filePath, ".")(0), FileFormat:=wdFormatPDF
End If
So then the real question(I guess) is how do you get "Application.FileDialog" to display the proper type you wish to save in under the "Save as type" drop down, and this has already been answered by #PatricK. Thanks everyone for the help, I apologize for the initial confused nature of this question.
I am surprised for SaveAs2 will bring you a prompt to be honest - Only a new document and .Save will bring you that prompt.
If you want to get something similar to that prompt, you use Application.FileDialog with type msoFileDialogSaveAs.
Use this code below (perhaps as an AddIn suits more):
Option Explicit
Sub MySaveAs()
Dim oPrompt As FileDialog, i As Long, sFilename As String
Set oPrompt = Application.FileDialog(msoFileDialogSaveAs)
With oPrompt
' Find the PDF Filter from Default Filters
For i = 1 To .Filters.Count
'Debug.Print i & " | " & .Filters(i).Description & " | " & .Filters(i).Extensions
' Locate the PDF filter
If InStr(1, .Filters(i).Description, "PDF", vbTextCompare) = 1 Then
.FilterIndex = i
Exit For
End If
Next
' Change the title and button text
.Title = "Saving """ & ActiveDocument.Name & """ to PDF format"
.ButtonName = "Save to PDF"
' Default name
.InitialFileName = ActiveDocument.Name
' Show the Prompt and get Filename
If .Show = -1 Then
sFilename = .SelectedItems(1)
Debug.Print "Final filename: " & sFilename
' Save the file as PDF
ActiveDocument.SaveAs2 sFilename, wdFormatPDF
End If
End With
Set oPrompt = Nothing
End Sub
Screenshot sample:

Issue using FileDialog Application

I have a bit of code which I am trying to improve but having some issues.
The code is currently:
Sub TestListFilesInFolder()
'Workbooks.Add ' create a new workbook for the file list
' add headers
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker) ' Tried using a FileDialog Application but had no luck
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Old File Path:"
Range("B3").Formula = "File Type:"
Range("C3").Formula = "File Name:"
Range("D3").Formula = "New File Path:"
Range("A3:H3").Font.Bold = True
ListFilesInFolder "L:\Pictures\A B C\B526 GROUP", True
' ListFilesInFolder fd, True ' I tried replacing the above line with this line but get an error
' list all files included subfolders
End Sub
Line 5 and 6 is a part I have added in where I am trying to get a file dialog to open where the user can choose the folder for the code to work on.
Also The commented out line near the bottom starting ListFilesInFolder is the one I tried inserting to replace the line above it.
The start of the next bit of code is:
Sub ListFilesInFolder(SourceFolderName As String, IncludeSubfolders As Boolean)
So it uses the folder and subfolders of that folder defined in the first sub.
Any help on this would be appreciated.
Regards,
Sam
You're passing fd as the first parameter to your ListFilesInFolder sub. This sub accepts a String as the first parameter, not a FileDialog.
Here's some sample code that, when executed, will open a file dialog and let the user select a folder. Once selected, it will print the path of the folder to B2. If no folder is selected (e.g. dialog is closed or canceled), B2 will contain the text No item selected.
I think you should create a new workbook and play around with this macro. Set a break point and walk through it, see what it's actually doing. Then you can alter it to make it work for your specific needs.
Public Sub SelectExportDestinationPath()
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then
sItem = "No item selected"
Else
sItem = .SelectedItems(1)
End If
End With
'if trailing slash is not found, add it
If Len(sItem) > 0 And InStr(Len(sItem), sItem, Application.PathSeparator, vbCompareText) = 0 Then
sItem = sItem & Application.PathSeparator
End If
Sheet1.Cells(2, 2).Value = sItem
Set fldr = Nothing
End Sub
make sure you have the appropriate reference picked:
Press Alt+F11 to open the VB Editor. In that window, choose menu items Tools -> References..., then look down the list for Microsoft Office XXX Object Library
It's 11.0 for Access 2003, 10.0 for Access 2002; 9.0 for Access 2000, 8.0 for Access 97 -- pick the right one.
Put a check mark in the box next to that reference, then close the dialog.
or, use the actual values, not the mso values
msoFileDialogOpen=1
msoFileDialogSaveAs=2
msoFileDialogFilePicker=3
msoFileDialogFolderPicker=4