Using VB6
Code.
CommonDialog1.DialogTitle = "Open File"
CommonDi开发者_如何学JAVAalog1.Filter = "*.*"
CommonDialog1.FilterIndex = 1
CommonDialog1.Flags = cdlOFNAllowMultiselect + cdlOFNExplorer
CommonDialog1.Flags = cdlOFNFileMustExist + cdlOFNHideReadOnly
CommonDialog1.CancelError = True
On Error Resume Next
CommonDialog1.ShowOpen
If Err Then
'MsgBox "Select Folder"
Exit Sub
End If
From the above code, i am selecting a file, But i don't want to select a file, I want to select only the folder. How to modify my code.
Need vb6 code Help?
It's been a while since I've had to do any visual basic work but I think instead of using the common dialog box for getting the name of a file to open you should use the SHBrowseForFolder function which is already part of the Windows API. Here's a link to a page that describes it's usage.
Update (2017): Provided link is broken but a backed-up version can be viewed on archive.org
To select a folder, you can use the Shell and Automation Component.
Private shlShell As Shell32.Shell
Private shlFolder As Shell32.Folder
Private Const BIF_RETURNONLYFSDIRS = &H1
Private Sub Command1_Click()
If shlShell Is Nothing Then
Set shlShell = New Shell32.Shell
End If
Set shlFolder = shlShell.BrowseForFolder(Me.hWnd, "Select a Directory", BIF_RETURNONLYFSDIRS)
If Not shlFolder Is Nothing Then
MsgBox shlFolder.Title
End If
End Sub
You will need to add a reference to shell32.dll
to your project. Use the Project/References... menu and then browse for shell32.dll
.
Or you can use the Windows API as Twotymz suggests.
This is an old thread, but maybe someone will be helped by this. This code works in VB6 for me:
Private Sub ChooseDir_Click()
Dim sTempDir As String
On Error Resume Next
sTempDir = CurDir 'Remember the current active directory
CommonDialog1.DialogTitle = "Select a directory" 'titlebar
CommonDialog1.InitDir = App.Path 'start dir, might be "C:\" or so also
CommonDialog1.FileName = "Select a Directory" 'Something in filenamebox
CommonDialog1.Flags = cdlOFNNoValidate + cdlOFNHideReadOnly
CommonDialog1.Filter = "Directories|*.~#~" 'set files-filter to show dirs only
CommonDialog1.CancelError = True 'allow escape key/cancel
CommonDialog1.ShowSave 'show the dialog screen
If Err <> 32755 Then ' User didn't chose Cancel.
Me.SDir.Text = CurDir
End If
ChDir sTempDir 'restore path to what it was at entering
End Sub
I though that is more general VBA question anyway, opening select folder dialog in VBA for Office >=2k3.
I could not believe that it is so hard, as I need same functionality. Little googling made it. Here is nice simple solution take a look
Function GetFolderName()
Dim lCount As Long
GetFolderName = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Show
For lCount = 1 To .SelectedItems.Count
GetFolderName = .SelectedItems(lCount)
Next lCount
End With
End Function
精彩评论