Select folder using browse button in VBA - vba

I have a requirement where I need to select a folder instead of a file, while clicking a browse button.
The code to select a file, while clicking the browse button will be as below.
Case "Browse"
DlgText "path", GetFilePath(,"*.*","C:\","Open sheet")
How to change this to select a folder, instead of a file.
Thanks in advance

Please, try the next way:
Case "Browse"
Dim folderPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select the necessary folder!"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select any folder..."
Exit Sub
End If
folderPath = .SelectedItems(1)
End With
'your existing code...
Edited:
If you work in Windows OS, even if ERStudio, which I am not fammiliar to, does not expose such a method, please try the next way, using VBScript objects:
Case "Browse"
Dim objSh As Object, objFold As Object, strStartFolder As String, strFolder As String
strStartFolder = "C:\" 'you can use here what starting folder you want
Set objSh = CreateObject("Shell.Application")
Set objFold = objSh.BrowseForFolder(0, "Select The necessary Folder", 0, strStartFolder)
If IsObject(objFold) Then strFolder = objFold.Self.Path
MsgBox strFolder 'use it where necessary and comment this testing line...
'your existing code...

Related

Open the file and save as another name

I want to create a new word file called "xxx_def_xxx" from selected word file called "xxx_docu_xxx".
So I select a file from dialog -> do something -> SaveAs with new file name.
It does work, but I'm getting "run time error 4160: Bad file name" if I select the file created from others, i.e., if the author is not me but another person.
I was struggling with this problem for couple of days but couldn't solve it.
Any help will be really thankful!
Private Sub CommandButton1_Click()
Dim fileOpen As FileDialog
Dim docuName As String, defName As String
Dim docu As Document
Set fileOpen = Application.FileDialog(FileDialogType:=msoFileDialogOpen)
With fileOpen
.Filters.Clear
.Filters.Add "Word Documents", "*.docx*"
.Title = "Select the docu"
.AllowMultiSelect = False
If .Show = -1 Then
docuName = .SelectedItems(1)
Else
Exit Sub
End If
End With
Set docu = Documents.Open(docuName)
'do something: remove or edit some texts in the file
defName = Replace(docu.Name, "docu", "def")
docu.SaveAs docu.Path & "\" & defName
docu.Saved = True
docu.Close
End Sub

Open Windows Explorer from Outlook to choose template [duplicate]

This question already has answers here:
Filepicker VBA to select file and store the file name not working
(2 answers)
Closed 3 years ago.
I am trying to write a macro that allows a user to select a .oft from a directory. I have been able to get a simple macro working that will open a specific .oft and modify the "from" field - this is what I have so far.
Sub EmailTemplateW10()
Set msg = Application.CreateItemFromTemplate("c:\test\test.oft")
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub
That works great, but there are numerous .oft files in the directory I am working with. I did find some articles that talk about setting up a toolbar with drop-downs and creating a macro for each .oft in the directory. I assume there has to be a better way than making a macro for each template.
I tried using this :
Sub EmailTemplateW10()
Set msg = Application.CreateItemFromTemplate(Demo)
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub
Function Demo()
Call Shell("explorer.exe" & " " & "C:\test\", vbNormalFocus)
End Function
Windows Explorer will come up - but the macro throws an error and stops when you acknowledge the error.
Is there perhaps some way to have the user select the file through explorer.exe and save the path of the selected file to a variable, and then pipe that into .CreateItemFromTemplate?
After some digging around I got this to work. I am obviously a VBA noob so i take no credit for the code - I was just able to mash it together and get it to work. Maybe someone in the future will find it helpful.
Public Function aBrowseForFile(aStartFolder As String) As String
On Error GoTo Err_txtBrowseForFile
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
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 = xlApp.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", "*.*"
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
Sub EmailTemplateW10()
Dim MyFileURL As String
MyFileURL = aBrowseForFile("C:\users\")
Set msg = Application.CreateItemFromTemplate(MyFileURL)
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub

Excel VBA How to prevent user from hitting cancel in msoFileDialogSaveAs

I am very new to VBA and I am creating a template for my boss. I want to force users to "save as" so that they don't overwrite the template. In other words, I'd like to disable the cancel button when the save as dialog box pops up.
Here is my code:
Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)
With fPth
.InitialFileName = CTAPath
.InitialFileName = CTAName & "_CAP DATA"
.Title = "Save with your CTA file"
.InitialView = msoFileDialogViewList
.FilterIndex = 2
If .Show = -1 Then
.Execute
End If
End With
I'm thinking I should create an ELSE statement within the IF statement but I can't figure out what it should be. I've tried searching and I'm not coming up with any solutions.
Thank you!
That's not the way to do this: if the users choose the file itself in the "Save as" filelist, you might end up in the same situation.
I'd advise you to make the file read-only, so nobody can change or overwrite it.
I'm not sure you're able to disable Cancel button, but there is workaround...
You can loop .Show method till user hits Save button ;)
For example:
Sub PreventCancel()
Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)
Dim result As Variant
With fPth
.InitialFileName = CTAPath
.InitialFileName = CTAName & "_CAP DATA"
.Title = "Save with your CTA file"
.InitialView = msoFileDialogViewList
.FilterIndex = 2
Do
result = .Show
Loop While result <> True
.Execute
End With
End Sub
[EDIT]
I'd suggest to use Application.GetSaveAsFilename Method (Excel) instead of FileDialog, because it gives you more control over it.
Please, read valuable comments to your question also.

Choosing a filepath to export .xlsx file VBA

I'm trying to write a bit of code that allows the user to choose the file path of a folder before exporting data in a separate .xlsx file to that folder. Its easy enough to look up a folder's path beforehand and hard code it in, but I want this program to allow the user to choose a folder each time. As it is, I have this function that utilizes the excel open file dialog box. From there, I am able to find the folder I need, and just copy the file path from the top bar and hit cancel. Here's the code:
Function GetFileDestination() As String
Dim DataObj As New MSForms.DataObject
'This MsgBox just tells the user what to do
MsgBox "To get the file Destination, the 'Open File' Dialog Box will open. Go to the folder_
you want to use, click on the bar at the top, and copy the destination. Then hit Cancel",_
vbOKOnly, "Finding the File Destination"
Application.Dialogs(xlDialogOpen).Show
DataObj.GetFromClipboard
GetFileDestination = DataObj.GetText
End Function
This does the job, but it seems pretty sloppy, since it forces the user to manually copy the file path needed and then cancel the open file dialog box.
Does anyone know a more creative and clean way about this while still keeping the same functionality?
Thanks in advance!
Function GetFolder(strPath As String) As String
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 GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Here's the description:
Application.FileDialog(msoFileDialogFolderPicker) - The folder dialog prompts the user to
select a directory path.
strPath - Default path which will be passed on to the function.
show - If the user chooses to cancel the dialog, the value '0' will be assigned, otherwise the value '-1' is assigned.
GetFolder = sItem - The path of the folder selected/opened is returned by this statement,
else Null is returned if Cancel button is clicked.
Hope this clears the overall logic used.

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