Load template and attach chosen file - vba

The aim of this project is to:
Load template from network personal drive (currently working)
Open Dialog Window, using Word (as that loads quicker for me), set to a different network folder (function achieved - just)
Choose and attach user chosen file (prefered option for multi-file selection but that was to complex and thus beyond the time I can afford to dedicate to the project)
Using previous filepath, build and apply the subject line based on the file name. (currently working)
The macro is called by a button in the Quick Access or Main Tool Bars.
The problems:
when the "Browse" window appears, it does so behind outlook/hidden UNLESS the macro code has been viewed in the editor at some time since Outlook was opened; every fix either show the entire Word program or seems to have no effect.
when you choose a file in the "Browse" and then click "OK", a second "Browse" window opens where you have to choose a file again and this time click "Open"; this second file is then the one that is attached to the email.<--FIXED
System Details (even though not all will be of importance)
Windows 7 64bit
Office Professional 2010
The Code
Sub New_Orders_Email()
Dim NewMail As Outlook.MailItem
Dim otherObject As Word.Application
Dim fd As Office.FileDialog
Dim fileaddress As String
Dim filename As String
On Error GoTo Final
'Set template to use
Set NewMail = Application.CreateItemFromTemplate("P:\Office Templates\Orders SCI - 1617.oft")
'Set to use Word for Attach File Dialog
Set otherObject = New Word.Application
otherObject.Visible = False
Set fd = otherObject.Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.InitialFileName = "R:\Science\Technician Documents\Budgets & Orders\2016 - 2017\Orders\"
.Show
End With
fd.Show
fileaddress = fd.SelectedItems(1)
'Aquire File Name in correct form for Subject Line
Dim MidStart As Long
MidStart = InStrRev(fileaddress, "\") + 16
Dim MidEnd As Long
MidEnd = InStrRev(fileaddress, ".")
filename = Mid(fileaddress, MidStart, MidEnd - MidStart)
'Load template, attach single file and apply correct Subject
NewMail.Display
NewMail.Attachments.Add (fileaddress)
NewMail.Subject = "Order No: " + filename
otherObject.Quit
Set otherObject = Nothing
Final:
End Sub

Your file Dialog is probably not shown, because of the line "otherObject.Visible = False"
Number (2) might be solved if you delete one of your "fd.Show". Looks like you call it twice...

Related

VBA - Application.FileDialog() - Object doesn't support this property or method (Error 438)

My code is simple.
I have copied it off of the VBA example site: https://learn.microsoft.com/en-us/office/vba/api/office.filedialog
Additionally, every other variation I can find online has the same problem.
All I am attempting is to open a File Dialogbox (Similar to a file explorer) where a user can select a folder or files.
However, I carry on getting this error:
It then highlights this line of code:
Additionally, I have added references to Microsoft Office 16.0 Object Library, and everything I can think of:
How do I fix this or get this to Run?
Thank You
Here is the Code:
Sub Main()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is aString,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the button.
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is aString that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example displays the path in a message box.
MsgBox "The path is: " & vrtSelectedItem
Next vrtSelectedItem
'The user pressed Cancel.
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
Disclaimer: I'm sure there is a better/more correct way to do this but it works for me in VBA for SolidWorks. I am not a real programmer. Just trying to help because I know how few resources there are on VBA programming in SW.
All I really did was add the Excel Object library and change Application to Excel.Application.
Despite what GSerg said, there can be an Excel.Application if you add the Excel object library as a reference.
Despite macropods condescension, you are not stuck with what SW provides or the generic file browser and you don't need to re-install Office or SW. The generic file browser doesn't show your Quick Access items. SolidWorks doesn't run on Mac OS. His "answer" does not work in SW VBA.
Here is my working function (started with code from here):
Function GetFolder(Title As String)
Dim folder As FileDialog
Dim selected_folder As String
Set folder = Excel.Application.FileDialog(msoFileDialogFolderPicker)
With folder
.AllowMultiSelect = False
.ButtonName = "Ok"
.Filters.Clear
.InitialFileName = Excel.Application.DefaultFilePath
.Title = Title
If .Show <> -1 Then GoTo NextCode
selected_folder = .SelectedItems(1)
End With
NextCode:
Debug.Print selected_folder
GetFolder = selected_folder
Set folder = Nothing
End Function
I added the Excel & Office Object Libraries to the default VBA SW:
If you have a way to do this that shows the Quick Access items without having to use the Excel Object Library I'm very interested!
I assume you're using a Windows system, since Application.FileDialog is not available/fully supported on Macs.
I suggest you start over, without adding a plethora of irrelevant references. The following works just fine without adding any to the default references:
Sub Demo()
Dim fd As FileDialog, vrtSelectedItem As Variant
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
MsgBox "The path is: " & vrtSelectedItem
Next
End If
End With
Set fd = Nothing
End Sub
If the code still doesn't work for you, a repair/reinstall of Office or your SolidWorks installation is most likely called for.
For code that works on Macs and PCs, see: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-msoffice_custom-mso_365hp/showing-dialogs-word-for-mac-vba/513ea974-378d-4ebe-95c3-a0221a9287ff

Open a Word 2013 legacy Open dialog in a specific folder

I have a simple Word macro that shows the legacy Open dialog.
Sub LegacyOpen()
DoEvents
Dialogs(wdDialogFileOpen).Show
End Sub
I’m now trying to get it to open in a specific folder.
"C:\Users\Paul Schroeter\Documents\Microsoft Word Documents".
After about an hour I have not found an macro argument or example of how to get it to do what I want it to do.
If you wonder why I need to do this, it’s because every time I use “Search documents” in the legacy Open dialog, it resets the Open dialog path to "C:\Users\Paul Schroeter\Documents", which is driving me insane, because I then have to change it back to the folder where I actually keep my Word documents.
A number of the built-in Word dialog boxes have "dialog box arguments" corresponding to some of the controls/settings in the dialog box. A list can be found here. These are not part of the Intellisense and are late-bound into the object model. The developer needs to know they exist and how to look them up and use them.
One of these built-in arguments is to set/read the file full name from the File/Open dialog box. In VBA the arguments are usually used in a With block. Putting the argument before the Show or Display method executes the setting before the dialog box is shown to the user. If it's placed after the method, then it's used to read the user's choice.
Sub WordFileOpen()
Dim dlg As Word.Dialog
Dim sPath As String
Set dlg = Application.Dialogs(wdDialogFileOpen)
sPath = "C:\Users\Paul Schroeter\Documents\Microsoft Word Documents"
With dlg
.Name = sPath
.Show
End With
End Sub
If you consider something different than Dialogs collection you could use FileDialogs property. Here is working example:
Sub OtherWindowType()
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.AllowMultiSelect = False
.InitialFileName = "c:\" '...your path here
.Show
End With
'if you want to open the file...
If FD.SelectedItems.Count > 0 Then
Documents.Open FD.SelectedItems(1)
End If
End Sub

Excel VBA: Importing/browsing files in folder

I have a concerned regarding importing/browsing files using VBA. It is working as expected, I can import or select files from the folder. However, there is a dialog box popped out every time I processed the selected file (see image below). Is it possible to remove this dialog box? Or is it because the file is too large to handle?
Here is my code for selecting the file from the folder:
Dim FSO As Object
Dim FD As Object
Set FSO = CreateObject("scripting.filesystemobject")
Set FD = Application.FileDialog(msoFileDialogFilePicker)
'select/browse file in folder path
If FD.Show = -1 Then
Filename = FD.SelectedItems(1)
Filename = FSO.getfile(Filename)
End If
txtBoxOld.Text = Filename
Thank you.
Setting Application.DisplayAlerts = True is a bit like just sticking your fingers in your ears and saying I CAN'T HEAR YOU. The problem is that it will mute every alert, not just the one you're concerned about.
If you want to purge the clipboard before the end of the subroutine, use Application.CutCopyMode=False and you won't get the error.

Saving File Path Using File Picker

I have written the below code via a user form with buttons. On the form, I have created three (3) separate command buttons that are to save different file paths to open existing excel workbooks. The idea is to have vba automatically open/close workbooks in a completely automated fashion.
Dim SCDMMRReport As FileDialog
Dim ActionClicked As Boolean
Set SCDMMRReport = Application.FileDialog(msoFileDialogFilePicker)
SCDMMRReport.InitialFileName = "J:\INS\CAS\G22 PRT Report"
SCDMMRReport.AllowMultiSelect = False
ActionClicked = SCDMMRReport.Show
If ActionClicked Then
SCDMMRReportCommandButton.Visible = False
SCDMMRReportLabel.BackColor = rgbLightGreen
SCDMMRCheckBox = True
Else
MsgBox ("No file selected!")
SCDMMRReportCommandButton.BackColor = rgbPink
SCDMMRReportLabel.BackColor = rgbPink
End If
Everything appears as it runs excellent, however when it comes time to call on this code later in the script (when I hit the execute command button), the file paths are not saved. Any advice is greatly appreciated!
Thanks,
Derek

MS Access 2010 - How can I tie an entry text box to a VBA command that opens a MS Word file based on user's entry?

Option Compare Database
Function Openword(conPath As String)
Dim appword As Word.Application
Dim doc As Word.Document
On Error Resume Next
Error.Clear
Set appword = GetObject(, "word.application")
If Err.Number <> 0 Then
Set appword = New Word.Application
appword.Visible = True
End If
Set doc = appword.Documents.Open(conPath, , True)
appword.Activate
Set doc = Nothing
Set appword = Nothing
End Function
Private Sub Command5_Click()
Dim mydoc As String
mydoc = "J:\3 - Client Services\1-Programs\12229709.docx"
Call Openword(mydoc)
End Sub
So far I have made the code that will open a specific file when the button on the form is clicked. However, there are a ton of these files that the user needs to be able to select and open. To keep it simple, I want them to be able to open the Word file by simply typing in the name of the file and clicking a button that will find and open it. The name of the file in the example above is simply 12229709.docx, but there are other files similar to it (e.g. 12172029, 12124057...) all in the same location. I want there to be a text box where the user can enter in the number and the button will check that specific folder for a file name with that number in it (without having to add the ".docx" if possible). How do I go about doing this?
EDIT - I forgot to mention that I cannot show the file path or use a file dialog box to allow the user to pick the file because the users that will be choosing the file do not have authorization to access this part of the network.
Try this out
Dim MyValue as Variant
MyValue = Inputbox("Enter File Name")
Dim MyDoc as String
MyDoc = "J:\3 - Client Services\1-Programs\" & MyValue & ".docx"
Call OpenWord(MyDoc)
Not sure if that is what you are looking for but I hope it helps.
I don't know why you'd want to make your user type in a file name when you can just open a file dialog and have them click on the right file.
Just put a command button on your form and include a line "Application.FollowHyperlink" plus this function name. The computer file associations can take care of the rest.
Sub Command()
Application.FollowHyperlink FileName()
End Sub
Public Function FileName() As String
Dim f As Object
' Must have object reference set to a MS Office Object Library for this to work.
Set f = Application.FileDialog(msoFileDialogFilePicker)
With f
.AllowMultiSelect = False
If .Show = -1 Then
FileName = .SelectedItems(1)
End If
End With
FileName = Nz(FileName, "")
End Function