How to select a folder only by using common dialog control - vb6

Using VB6
Code.
CommonDialog1.DialogTitle = "Open File"
CommonDialog1.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

Related

MS Access 2016 File Browse Button Issues

I am using the script listed below (I honestly stole this probably from this very site) for a browse button on a form. The task is simply to start up MS File Dialog box so that a file (in this case an image file) can be selected. Once you select the record and click ok it then pastes the file name and location into a field.
Viewing the table the file name and location is pasted just as it should be. The problem comes in with a report I built. I have an image set to display with the control source linked back to that file address field. It will not display the image though.
However, if I manually type the same address character for character or even “copy”, delete, and then “paste” the same exact entry into the field the image then displays just fine on the report.
I have checked to make sure there are no spaces or characters anywhere there shouldn’t be. I am at a loss here.
Any help would be greatly appreciated and I will gladly give you my first born. Ok maybe not the first I like him but you can have the second one, she’s hell.
Private Sub Command67_Click()
On Error GoTo SubError
'Add "Microsoft Office 14.0 Object Library" in references
Const msoFileDialogFilePicker As Long = 3
'Dim FD As Office.FileDialog
Dim FDialog As Object
Dim varfile As Variant
Set FDialog = Application.FileDialog(msoFileDialogFilePicker)
EmployeePicture = ""
' Set up the File Dialog
Set FDialog = Application.FileDialog(msoFileDialogFilePicker)
With FDialog
.Title = "Choose the spreadsheet you would like to import"
.AllowMultiSelect = False
.InitialFileName = "C:\Users\" 'Folder picker needs trailing slash
.Filters.Clear
.Filters.Add "All", "*.*"
If .Show = True Then
If .SelectedItems.Count = 0 Then
'User clicked open but didn't select a file
GoTo SubExit
End If
'An option for MultiSelect = False
'varFile = .SelectedItems(1)
'EmployeePicture = varFile
'Needed when MultiSelect = True
For Each varfile In .SelectedItems
EmployeePicture = EmployeePicture & varfile & vbCrLf
Next
Else
'user cancelled dialog without choosing!
'Do you need to react?
End If
End With
SubExit:
On Error Resume Next
Set FDialog = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & " = " & Err.Description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit
End Sub

Vba - returning Shell explorer current path and then close it

First of all, I must say that I'm running a code in a machine that has very few references installed and no Office at all.
I need to open an "explorer.exe" instance with the Shell command, browse through folders, enter in a selected (or newly created) one and finally click on "Ok" on a MsgBox (which pops up simultaneously) to close the Shell and return the selected folder path to a variable.
I have no idea how to achieve that. When I use CurDir, I end up getting a folder which is not the selected one.
Code used (which didn't work):
Sub BrowseForFolder()
ActualDir = "D:\"
Call Shell("C:\Windows\explorer", ActualDir, 1)
If Msgbox("Browse into folder or create a new one and then browse into it, then click ok", vbOkOnly, "Browse") = vbOk Then
' here should be the command to return the path. The following doesn't work since it returns always "D:\"
ActualDir = CurDir
End If
' Here I have to close the Shell - I have no idea what to write to do it
End Sub
Below the code suggested by LS_dev which worked totally:
Private Sub SelectFolder_Click()
Dim objShell As Shell
Had to add the shell references
Dim ssfWINDOWS As Long
Dim objFolder As Folder2
for some reason "Folder" doesn't work
ssfWINDOWS = 36
Set objShell = New Shell
Set objFolder = objShell.BrowseForFolder(0, "Select Folder", 0, "D:\")
If (Not objFolder Is Nothing) Then
FolderName = objFolder.Self.path
End If
Set objShell = Nothing
End Sub

How to get Volume Serial Number using Visual Basic 2010?

I'm trying to get Volume Serial Number using Visual Basic 2010,
Is there a whole code example that shows me how to do this?
Thanks
I guess the simplest answer to my question was given by:
Hans Passant:
From his link,
I just copied and pasted this function and it works for Microsoft Visual basic 2010 express, Without any modifications
Public Function GetDriveSerialNumber() As String
Dim DriveSerial As Long
Dim fso As Object, Drv As Object
'Create a FileSystemObject object
fso = CreateObject("Scripting.FileSystemObject")
Drv = fso.GetDrive(fso.GetDriveName(AppDomain.CurrentDomain.BaseDirectory))
With Drv
If .IsReady Then
DriveSerial = .SerialNumber
Else '"Drive Not Ready!"
DriveSerial = -1
End If
End With
'Clean up
Drv = Nothing
fso = Nothing
GetDriveSerialNumber = Hex(DriveSerial)
End Function
I would like to thank everyone for their help,
And i apologize for repeating the question,
I did do a google search and a stackflow search,
But my search was"
"get hard drive serial number in visual basic 2010"
So this website did not show up,
Thanks again
This thread here http://social.msdn.microsoft.com/Forums/vstudio/en-US/43281cfa-51c8-4c35-bc31-929c67abd943/getting-drive-volume-serial-number-in-vb-2010 has the following bit of code that you could use/adapt.
I made a piece of code for you to show all drive information.
The Volume serial number is included you can get that by simple
putting some more if's in the code
Imports System.Management
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim drivetype() As String = {"Unknown", "NoRootDirectory", _
"RemoveableDisk", "LocalDisk", "NetworkDrive", "CompactDisk", "RamDisk"}
Dim allDrives() As String = Environment.GetLogicalDrives()
For Each drive In allDrives
Dim win32Drive As String = _
"Win32_LogicalDisk='" & drive.Substring(0, 2) & "'"
Dim Disk As System.Management.ManagementObject _
= New System.Management.ManagementObject(win32Drive)
Me.ListBox1.Items.Add(drive.ToString & drivetype(CInt((Disk("DriveType").ToString))))
For Each diskProperty In Disk.Properties
If Not diskProperty.Value Is Nothing Then
Me.ListBox1.Items.Add("---" & diskProperty.Name & "=" & diskProperty.Value.ToString)
End If
Next
Next
End Sub
End Class

checking format to a text box

I need a method to check the contents of the text entered to make sure they are correctly entering a folder path. So it needs to be in the format of:
Drive Letter :\ Folder
e.g. C:\My Documents
If they haven't typed in that format I need to stop and show a message telling them to double check.
I have tried the Filter function but I haven't quite got it to work. Any help would be awesome. I don't have any code to show because I am nto sure where to start.
I also tried the common dialog, but the user jsut needs the type the path, not select the file. All I want to check is if the text type is within that format DRIVE:\FOLDER, that is it. So if the type "BLAH" in the text bax a message says Hey you type a correct path.
In VB6, to test whether your text contains a valid folder:
If Len(Dir("c:\My Documents", vbDirectory))>0 Then
'it's a folder
End If
Have you thought of implemeting the common dialog control to allow the selection of a correct folder instead - it'll be much more likely to be accurate.
Some example code of folder browsing from here:
Private Sub Command1_Click()
On Error Resume Next
Const WINDOW_HANDLE = 0
Const NO_OPTIONS = 0
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(WINDOW_HANDLE, "select folder:", NO_OPTIONS, "C:Scripts")
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
objPath = Replace(objPath, "", "\")
Print objPath
End Sub
Alternatively you could validate the folder first you could check for ":\" using eith instr or mid
then you could validate the folder and even include an option to create it if not present with the filesystemobject (needs a reference set) here it is in function form, you can pass the contents of the textbox for validation.
Function DirExists(pFile As String, Optional pCreate As Boolean = False)
'
Dim fso As New FileSystemObject
Dim vPath As Variant
Dim sPath As String
Dim y As Variant
DirExists = False
If fso.FolderExists(pFile) Then
DirExists = True
Else
If pCreate Then
vPath = Split(pFile, "\")
For Each y In vPath
sPath = sPath & y & "\"
If Not fso.FolderExists(sPath) Then
fso.CreateFolder (sPath)
If fso.FolderExists(pFile) Then
DirExists = True
Exit Function
End If
End If
Next
End If
End If
End Function

How do I save an entire VB6 project to a new folder? Modules and all

How do I save an entire VB6 project to a new folder? Modules and all. I'm in a position where I need to work with some old VB6 projects. I'd like to save them to a new folder but when I save the project, all that is saved is the vbp file. No modules, no frm files. I want to be able to save all the info to a single folder without moving each BAS file one at a time. Is this even possible?
Addition: The first 2 replies make good sense. But my problem is that the BAS modules seem to be scattered all over the place. Making Windows Explorer do the work a bit tricky. If I have to I will but was looking for an easier way.
Thanks
Given the new "addition" to the question:
Move the VBP and the files in Windows Explorer to a completely new directory.
Open the VBP in a text editor and change any absolute paths to relative paths. VBP files are simple text files, and the format is even documented in the VB6 manual.
Here's an example. This evil VBP below has many absolute paths
Type=Exe
Form=c:\who\knows\where\B_Form.frm
Module=CModule; z:\magic\mapped\network\drive\heehee\C_Module.bas
Class=DClass; x:\personal\usb\stick\D_Class.cls
It would be changed to this benign VBP, which references local copies of the files. You can use relative paths for subdirectories.
Type=Exe
Form=B_Form.frm
Module=CModule; C_Module.bas
Class=DClass; subdirectory\D_Class.cls
If you mean from within Visual Studio, I don't think you can except by doing Save As for each file...
But the simpler approach is to just use Windows Explorer and copy the whole folder structure for the solution into another folder, (or do a recursive "Get" from your source code repository to a different local destination), and then open the solution or project file in the new location... The pointers in the project file that tell Visual Studio where 5all the individual source code and other files are located are generally all stored as relative paths, relative to the folder that the project file is in...
It's been a while since I used VB6, but I'd be tempted to move them using Windows Explorer, then manually edit the VBP file to point to the new locations afterwards. If I remember right, relative paths are fine in the VBP, so you may not even need to manke any changes.
Unbind from source control, if capable/appropriate.
Check into source control as a brand new solution/project
Recursive 'get' from your SCM into a new directory.
There's your new copy.
Create a VB6 Add-in. You can download it from: http://pan.baidu.com/s/1CXO3k
Or you can use below code to create your own.
Option Explicit
Public VBInstance As VBIDE.VBE
Public Connect As Connect
Private Sub CancelButton_Click()
Connect.Hide
End Sub
Private Sub OKButton_Click()
On Error Resume Next
Dim strProject As String
Dim strPath As String
Dim strPath2 As String
Dim strFile As String
Dim strPrjFile As String
Dim rst As VbMsgBoxResult
Dim m, n As Long
Dim col2 As Collection, col As Collection
Dim vbCom As VBComponent
Dim fso As FileSystemObject
Dim ts As TextStream
Dim f1 As String, f2 As String
strProject = Me.VBInstance.ActiveVBProject.FileName
strPath = ParseFileName(strProject, strPrjFile)
strPath2 = setFolder
If strPath = "" Or strPath = strPath2 Then
MsgBox "target folder is invalid or same as the project folder. Can't copy."
Exit Sub
End If
Set col2 = New Collection
Set col = New Collection
Set fso = New FileSystemObject
Set ts = fso.CreateTextFile(strPath2 & "\wemeet.log", False)
For m = Me.VBInstance.ActiveVBProject.VBComponents.Count To 1 Step -1
Set vbCom = Me.VBInstance.ActiveVBProject.VBComponents(m)
For n = 1 To vbCom.FileCount
f1 = vbCom.FileNames(n)
ParseFileName f1, strFile
f2 = strPath2 & "\" & strFile
fso.CopyFile f1, f2
col.Add f1
col2.Add f2
ts.WriteLine "" & Now() & " [Move]: " & f1
ts.WriteLine "" & Now() & " [To ]: " & f2
ts.WriteBlankLines 1
Next
Me.VBInstance.ActiveVBProject.VBComponents.Remove vbCom
Next
For m = 1 To col2.Count
Me.VBInstance.ActiveVBProject.VBComponents.AddFile col2.Item(m)
ts.WriteLine "" & Now() & " [Add]: " & col2.Item(m)
ts.WriteBlankLines 1
Next
Me.VBInstance.ActiveVBProject.SaveAs strPath2 & "\" & strPrjFile
ts.WriteLine "" & Now() & " [SaveAs]: " & strPath2 & "\" & strPrjFile
ts.WriteBlankLines 1
ts.Close
fso.OpenTextFile strPath2 & "\wemeet.log"
Set fso = Nothing
Set col = Nothing
Set col2 = Nothing
Set vbCom = Nothing
Connect.Hide
End Sub
Private Function ParseFileName(ByVal sPath As String, ByRef sFile As String) As String
Dim fso As New FileSystemObject
If fso.FileExists(sPath) Then
ParseFileName = fso.GetParentFolderName(sPath)
sFile = fso.GetFileName(sPath)
Else
ParseFileName = ""
sFile = ""
End If
Set fso = Nothing
End Function
Private Function setFolder() As String
Dim objDlg As Object
Dim objStartFolder As Object
Set objDlg = CreateObject("Shell.Application")
Set objStartFolder = objDlg.BrowseForFolder(&H0, "Select a folder", &H10 + &H1)
If InStr(1, TypeName(objStartFolder), "Folder") > 0 Then
setFolder = objStartFolder.ParentFolder.ParseName(objStartFolder.Title).Path
End If
Set objDlg = Nothing
End Function

Resources