1

I'm using the FileDialog to select a folder for use with OutputTo. I have coded the file name. When I select a folder, I get a properly format string ie: "C:\Documents\export.xls". However, when I select the root folder, I get a improper format ie: "C:\\export.xls". Note the double slashes.

Any thoughts on what is causing this behavior?

Function selectFolder()
Dim fdf As FileDialog, FolderName As String


On Error GoTo ErrorHandler
 

Set fdf = Application.FileDialog(msoFileDialogFolderPicker)

fdf.InitialFileName = getdbpath
 
fdf.AllowMultiSelect = False
 
If fdf.Show = True Then
    If fdf.SelectedItems(1) <> vbNullString Then
        FolderName = fdf.SelectedItems(1)
    End If
Else
    'Exit code if no file is selected
    End
End If
 
'Return Selected FileName

selectFolder = FolderName & "\AccountOutput.xls"
'Debug.Print FolderName

Set fdf = Nothing

Exit Function

ErrorHandler:
Set fdf = Nothing
MsgBox "Error " & Err & ": " & Error(Err)
 
End Function
Michael C
  • 59
  • 4
  • 2
    I don't get double backslash, just single. Edit question to provide your code. Are you using VBA? Add tag for programming language. – June7 Feb 22 '21 at 15:00
  • Updated the comment to include code. – Michael C Feb 22 '21 at 16:09
  • 1
    Most likely `FolderName` ends in a backslash for the root (C:\\) but not for a subfolder (C:\Users). Microsoft apps have always been a little sloppy (IMO) that way. When I write code I always ensure that a folder name ends in a backslash (C:\Users\\) but that's just me. TL;DR - Instead of just appending `"\AccountOutput.xls"` you need to check if `FolderName` already ends with a backslash. – Gord Thompson Feb 22 '21 at 18:01

1 Answers1

1

This is how the folder picker works - you need to handle both cases, e.g.

If Right$(FolderName, 1) <> "\" Then
    FolderName = FolderName & "\"
End If

selectFolder = FolderName & "AccountOutput.xls"

See e.g.

https://superuser.com/questions/270418/check-for-trailing-in-string-returned-from-msofiledialogfolderpicker-excel-vb

Andre
  • 26,751
  • 7
  • 36
  • 80