Browse for a folder in VBA

DHS100

Board Regular
Joined
May 21, 2006
Messages
149
Hi,

I'm having a bit of trouble getting this to work. All I want is for a dialogue box to pop up so the user can select a folder and to be able to default to the last folder they visited. I've seen lots of ways to do this but there is a problem with the best method I've found so far. I'm using this:

Set ShellApp = CreateObject("Shell.Application").BrowseForFolder(0, "Please choose a folder", 0, "C:\test\")

The problem is that there is no way to go up a level in the directory structure. The above code mean you couldn't go to "C:\". Any help with this would be very much appreciated.

Thanks
 
As a further edit, when I type this:

Application.FileDialog(msoFileDialogFilePicker) with .allowmultiselect = true

I can select multiple files and it works, but I need to be able to pick multiple folders which it lets me select, but once I click 'OK' nothing happens.

Although, when I type this:

Application.FileDialog(msoFileDialogFolderPicker) with .allowmultiselect = true

I cannot select multiple folders and inherently I cannot select files because it's a 'folder picker' only.
 
Upvote 0

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
I have the following code that I found online and modified that works with what I'm trying to do.

Code:
On Error Resume Next
     
    Set wbCodeBook = ThisWorkbook
     
    With Application.FileSearch
        .NewSearch
         'Change path to suit
        .LookIn = "S:\Travel\Public\Travel Assistance\Summer 2011\Schedules"
        .FileType = msoFileTypeExcelWorkbooks
         '.Filename = "Book*.xls"
Dim iTotals As Integer
        Dim strTabname As String
        Dim iCounter As Integer
        
        iCounter = 1
                         
        If .Execute > 0 Then 'Workbooks in folder
            For lCount = 1 To .FoundFiles.Count 'Loop through all.
                 'Open Workbook x and Set a Workbook variable to it
                Set wbResults = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)
                
                iTotals = Worksheets.Count
                strTabname = Left(ActiveWorkbook.Name, 3)
                Sheets(iTotals).Copy after:=Workbooks("master.xls").Sheets(iCounter)
                ActiveSheet.Name = strTabname
                                
                wbResults.Close SaveChanges:=True
                
                iCounter = iCounter + 1
                 
            Next lCount
        End If
    End With

Is there a way rather than having the folder path programmed into the macro, I could have a box popping up asking the user to navigate to the desired folder? I tried to use what you have here, but I couldn't figure out how to do so. Thanks a million.
 
Upvote 0
This code builds on the previous post and should get the job done.

Code:
Option Explicit
Sub ImportDir()
    Dim wb As Workbook
    Dim ws As Worksheet
    
    Dim FileName As String
    Dim Folder As String
    
    Set wb = ThisWorkbook
    
    'Get the Directory Path
    Folder = GetFolder
    
    'Get the first file that matches the *DAT criteria
    FileName = Dir(Folder & "\*.Dat")
    
    Do While Len(FileName) > 0
        Debug.Print FileName
        wb.Sheets.Add After:=wb.Sheets(wb.Sheets.Count)
        Set ws = wb.ActiveSheet
        
        'Import the CSV File
        ImportCSV FileName, ws
        
        'Get the next file in the directory
        FileName = Dir
    Loop
End Sub
Function GetFolder() As String
    'Locate the Folder Name
    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
End Function
Function ImportCSV(ByVal FileName As String, ws As Worksheet)
        Debug.Print "******" & FileName
        
        With ws.QueryTables.Add(Connection:= _
            "TEXT;" & FileName, Destination:=Range("A$1"))
        .Name = FileName
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Function

Sub Macro3()
'
' Macro3 Macro
'
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Documents and Settings\cpelab\Desktop\new  2.dat", Destination:= _
        Range("$A$1"))
        .Name = "new  2"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    
End Sub
 
Upvote 0
Hi Excel Gurus :smile:

How could I use this macro to insert pictures into a cell using a dialog box to selelct a picture file?
After clicking on a button "Insert Drawing" a generic windows dialog box should pop up asking me to select a picture I'd like to insert. After selecting required picture it would be inserted into a cell with resizing option to match cell width but locked aspect ration (cell height would adjust to keep original aspect ratio). Inserted picture need to be moving and scaling with cells. Please help
 
Upvote 0
Hi Excel Gurus :smile:

How could I use this macro to insert pictures into a cell using a dialog box to selelct a picture file?
After clicking on a button "Insert Drawing" a generic windows dialog box should pop up asking me to select a picture I'd like to insert. After selecting required picture it would be inserted into a cell with resizing option to match cell width but locked aspect ratio (cell height would adjust to keep original aspect ratio). Inserted picture need to be moving and scaling with cells. Please help

Hi Steve, this will not answer your question entirely but may be useful to get you started:

Dim filselect As String

filselect = Application.GetOpenFilename( _
FileFilter:="Picture Files (*.png;*.jpg),*.png;*.jpg", _
Title:="Select Picture")

With ActiveSheet.Pictures.Insert(filselect)
.Left = Range("a1").Left
.Top = Range("a1").Top
End With
 
Upvote 0
Richard:

I'm trying to use your code as part of another macro that selects a set of text and exports it to a .CSV file. Is there a way to insert your function as a variable that can be referenced instead of C:\Temp\?

Here is what I've got so far:

Sub Select_Export_Values()


Sheets("sheet1").Select
Range("F1:H1").Select
Range(Selection, Selection.End(xlDown)).Select

' Dimension all variables.
Dim DestFile As String
Dim FileNum As Integer
Dim ColumnCount As Integer
Dim RowCount As Integer
Dim TodaysDate As String
TodaysDate = Format(Date, "YYYYMMDD")



' Prompt user for destination file name.
DestFile = "C:\Temp\" & InputBox("Enter Name", "Export to CSV") & TodaysDate & ".csv"


' Set the file destination


' Obtain next free file handle number.
FileNum = FreeFile()

' Turn error checking off.
On Error Resume Next


' Attempt to open destination file for output.
Open DestFile For Output As #FileNum


' If an error occurs report it and end.
If Err <> 0 Then
MsgBox "Cannot Save File: " & DestFile
End
End If


' Turn error checking on.
On Error GoTo 0


' Loop for each row in selection.
For RowCount = 1 To Selection.Rows.Count


' Loop for each column in selection.
For ColumnCount = 1 To Selection.Columns.Count


' Write current cell's text to file with quotation marks.
Print #FileNum, """" & Selection.Cells(RowCount, _
ColumnCount).Text & """";


' Check if cell is in last column.
If ColumnCount = Selection.Columns.Count Then
' If so, then write a blank line.
Print #FileNum,
Else
' Otherwise, write a comma.
Print #FileNum, ",";
End If
' Start next iteration of ColumnCount loop.
Next ColumnCount
' Start next iteration of RowCount loop.
Next RowCount


' Close destination file.
Close #FileNum

End Sub
 
Upvote 0
Re: Folder temporarily locked after FileDialog(msoFileDialogFolderPicker)

Because it doesn't happen in 2003, it could be a bug.

Actually, I have seen this behavior in 2003. My take on it is that, after automated processing of files, the folder in which those files exist can't be deleted, renamed, moved, etc., because Excel maintains a “claim” on that folder as its current directory. To resolve this issue, just reset Excel’s current directory to be a different folder, such as the folder in which the Excel workbook itself resides. Here's an example of how to do that using a file system object:


  1. This example requires a reference to "Microsoft Scripting Runtime" be set.
  2. Add code similar to the following:

Code:
    Dim FSO As Scripting.FileSystemObject
    Dim DefaultPath As String
 
    Set FSO = New Scripting.FileSystemObject
    DefaultPath = FSO.GetAbsolutePathName(ThisWorkbook.Path)
   
    ‘Do whatever file processing from the data-source folder…
 
    ChDir DefaultPath   'Reset Excel's current directory to be this workbook file's directory, in order to
                        'release Excel's claim on the data-source directory, so it can be deleted, renamed,
                        'moved, etc.
 
Upvote 0
Re: Folder temporarily locked after FileDialog(msoFileDialogFolderPicker)

Hi All,

i currently have macro for bulk importing files into an excel sheet which is working great, except everytime i run it i have to edit the VBA to the new file path, i have read through this thread but im still very new to all this and not sure where to add the code without breaking my original code.

Code:
[COLOR=#0000FF]Sub[/COLOR] ImportText()    [COLOR=#0000FF]Dim[/COLOR] s [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]String[/COLOR], s1 [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]String[/COLOR]
    [COLOR=#0000FF]Dim[/COLOR] ImportFile [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]String[/COLOR]
    [COLOR=#0000FF]Dim[/COLOR] sSplit() [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]String[/COLOR]
    [COLOR=#0000FF]Dim[/COLOR] sPath [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]String[/COLOR]
    [COLOR=#0000FF]Dim[/COLOR] iCol [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]Integer[/COLOR], iRow [COLOR=#0000FF]As[/COLOR] [COLOR=#0000FF]Integer[/COLOR]
    
    [COLOR=#008000]'Change where necessary
[/COLOR]    sPath = [COLOR=#800000]"C:\Temp\"[/COLOR][COLOR=#008000]
[/COLOR]    
    ImportFile = Dir(sPath & [COLOR=#800000]"*.txt"[/COLOR])
    
    [COLOR=#0000FF]Do[/COLOR] Until ImportFile = [COLOR=#800000]""[/COLOR]
        s1 = [COLOR=#800000]""[/COLOR]
        iCol = iCol + 1
        iRow = 1[COLOR=#008000]
[/COLOR]        Open sPath & ImportFile [COLOR=#0000FF]For[/COLOR] Input [COLOR=#0000FF]As[/COLOR] #1
            [COLOR=#0000FF]Do[/COLOR] Until EOF(1)
                Line Input #1, s
                s1 = s1 & s
               [COLOR=#0000FF]If[/COLOR] [COLOR=#0000FF]Not[/COLOR] EOF(1) [COLOR=#0000FF]Then[/COLOR] s1 = s1 & vbCrLf
            [COLOR=#0000FF]Loop[/COLOR]
            
        Close #1


        sSplit = [COLOR=#0000FF]Split[/COLOR](s1, vbCrLf)
        [COLOR=#0000FF]For[/COLOR] i = 0 [COLOR=#0000FF]To[/COLOR] [COLOR=#0000FF]UBound[/COLOR](sSplit)
            Cells(iRow, iCol) = sSplit(i)
            iRow = iRow + 1
        [COLOR=#0000FF]Next[/COLOR] i
        ImportFile = Dir
    [COLOR=#0000FF]Loop[/COLOR]
     [COLOR=#0000FF]End[/COLOR] [COLOR=#0000FF]Sub[/COLOR]

here is my code and i want to be able to select the folder with the text files in, instead of having to edit the sPath = "C:\Temp" everytime
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,214
Messages
6,170,771
Members
452,353
Latest member
strainu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top