Creating Subfolders in VB2010? - vba

I'm in the position of needing to make a bunch of folders for my PC so I decided to turn it in to a coding task. I've managed to make it so the user types in the location they want the folders to go into as well as each line of the other text box being the title for a new folder.
Here's the problem. I ideally would like to put multiple folders inside each folder without running the program again. The textbox would look something like this and would result in file 1,2 in folderA and file 3,4 in folderB;
FolderA
File 1
File 2
FolderB
File 3
File 4
Here is the code I've done so far.
Dim Address As String = TextBox1.Text
For i As Integer = 0 To RichTextBox1.Lines.Count - 1
My.Computer.FileSystem.CreateDirectory(Address + (RichTextBox1.Lines(i)))
Next
Do you know what I would have to add to my code so that it includes sub-folders?
(I haven't been learning long so I'm sorry if the answer is really obvious.)

#punintentional
The code below will do exactly what you asked for. You HAVE to make sure you have a reference set to the Microsoft Office Object Library. You do this by going to Tools>References and find the appropriate on. I designed the below code with Microsoft Office 12 Object Library. If you are using Office 2010, I think the Reference will be for Microsoft Office 14 Object Library.
Option Explicit
Public Sub DirectorySelect()
Dim diaFileDialog As FileDialog
Dim blDirSelected As Boolean
Dim strBaseDirectory As String
Dim strA_Dir As String
Dim StrB_Dir As String
' set up a MS Office file dialog box to select a folder/directory
Set diaFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
With diaFileDialog
.AllowMultiSelect = False ' user may only select one base folder
.Title = "Select the base director" ' title of the dialog box
blDirSelected = .Show ' the .show method will return false if the user does not select a directory
If blDirSelected = True Then ' a directory was selected
strBaseDirectory = .SelectedItems(1) ' put the directory into a variable
strBaseDirectory = strBaseDirectory & "\" ' the returned directory needs a trailing backslash
' These steps will jump to the other sub procedure to make the desired folders
MakeNewDir _
BaseDirectory:=strBaseDirectory, _
AddDirectory:="FolderA"
strA_Dir = strBaseDirectory & "FolderA" & "\"
MakeNewDir _
BaseDirectory:=strA_Dir, _
AddDirectory:="Folder1"
MakeNewDir _
BaseDirectory:=strA_Dir, _
AddDirectory:="Folder2"
MakeNewDir _
BaseDirectory:=strBaseDirectory, _
AddDirectory:="FolderB"
StrB_Dir = strBaseDirectory & "FolderB" & "\"
MakeNewDir _
BaseDirectory:=StrB_Dir, _
AddDirectory:="Folder3"
MakeNewDir _
BaseDirectory:=StrB_Dir, _
AddDirectory:="Folder4"
End If
End With
End Sub
Public Sub MakeNewDir(ByVal BaseDirectory As String, ByVal AddDirectory As String)
If Dir(BaseDirectory, vbDirectory) = vbNullString Then
MkDir BaseDirectory
End If
If Right(BaseDirectory, 1) <> "\" Then
BaseDirectory = BaseDirectory & "\"
End If
MkDir BaseDirectory & AddDirectory
End Sub

Related

Programmatically copy a folder (in a way that mimics a user copy/paste) and update a Progress Bar during the copy?

I would like to simulate a folder copy exactly how it would happen if a user copy/pasted it in Windows Explorer (keep all the file/directory attributes, copy all subfolders and files in the same structure, etc.), and be able to update a progress bar during the copy.
FileSystem.Copy is a wonderful function that would mimic a user copy/paste, but I am unable to update a progress bar during the copy using that function.
The only way I have found to be able to achieve this is to write a custom function, so the ProgressBar.Maximum can be set to the size of the Folder and the ProgressBar.Value is updated after each individual file copy.
This function is becoming a lot of code to achieve something that seems simple. I also cannot disregard the notion that since this is customized that I am doing something wrong that I just don't know to test for. For example, had the folder I was testing with not had empty subfolders and hidden folders, I never would have adjusted for those things.
So I have to wonder if I am overlooking something much simpler to achieve this same goal.
My code is as follows:
Private Sub CopyFolderWithProgress(folderToCopy As String, newFolder As String, progBar As ProgressBar)
'Validate folder to copy
If Directory.Exists(folderToCopy) Then
If folderToCopy.Substring(folderToCopy.Length - 1) <> "\" Then
folderToCopy &= "\"
End If
Else
MsgBox("Invalid directory given: " & folderToCopy)
End
End If
'Validate new folder
If Directory.Exists(newFolder) Then
If newFolder.Substring(newFolder.Length - 1) <> "\" Then
newFolder &= "\"
End If
Else
MsgBox("Invalid directory given: " & newFolder)
End
End If
'Create folderToCopy as a new subfolder of newFolder
newFolder &= New DirectoryInfo(folderToCopy).Name & "\"
Dim di As DirectoryInfo
di = Directory.CreateDirectory(newFolder)
di.Attributes = New DirectoryInfo(folderToCopy).Attributes
'Create all subfolders
For Each thisDir In Directory.GetDirectories(folderToCopy, "*", SearchOption.AllDirectories)
Dim thisDirRelative = thisDir.Remove(0, Len(folderToCopy))
di = Directory.CreateDirectory(newFolder & thisDirRelative)
di.Attributes = New DirectoryInfo(thisDir).Attributes
Next
'Determine size of all files for progress bar
Dim dirSize As Long
For Each curFile In Directory.GetFiles(folderToCopy, "*", SearchOption.AllDirectories)
dirSize += FileLen(curFile)
Next
'Set progress bar 100% to size of all files
progBar.Value = 0
progBar.Maximum = dirSize
'Copy all files into correct folder and update progress bar
For Each curFile In Directory.GetFiles(folderToCopy, "*", SearchOption.AllDirectories)
'Get name of file
Dim curFileName = Path.GetFileName(curFile)
'Determine if file is in a subfolder of fileTopCopy
Dim curFileDir = Path.GetDirectoryName(curFile) + "\"
Dim curFileSubfolders = curFile.Substring(0, curFile.IndexOf(curFileName)).Replace(folderToCopy, "")
'Copy file
If File.Exists(curFile) Then
File.Copy(curFile, newFolder & curFileSubfolders & curFileName)
Else
Console.Write("Issue copying a file that should exist in source folder: " & curFile)
End If
'Update Progress Bar
progBar.Value += FileLen(curFile)
Next
End Sub

VBA: Code for creating subfolders and folders not working

I got this code from an online source and cant figure out what I have to change, for it to work, the folders are not being created in the desired location and I am unaware of where they are be created if any where?
Within the excel I have 3 command buttons, one to save the file to a specified location, one to email it to a collegue and lastly the command button which I am having issue with. Ill include images below.
And is it possible to cause a chain reaction between the codes, that once one is completed then the other will begin, as I can get them to work as they are on there own atm.
enter image description here
Mkdir can only create a single directory. You are trying to make two by supplying "9999 William Cox ltd\BRAKEL".
Make "9999 William Cox ltd" first, then make its child directories.
Here is some code that will generate all of the sub directories via a loop:
Add these functions to your code module:
Private Function makeDir(parentDir As String, childDir As String) As String
'Checks if supplied directory name exists in current path, if not then create.
childDir = parentDir & _
IIf(Left(childDir, 1) = "\", "", "\") & _
childDir & _
IIf(Right(childDir, 1) = "\", "", "\")
On Error Resume Next
MkDir childDir
On Error GoTo 0
makeDir = childDir
End Function
Public Sub makePath(parentDir As String, childPath As String)
Dim i As Integer
Dim subDirs As Variant
Dim newdir As String
Dim fPath As String
fPath = parentDir
subDirs = Split(childPath, "\")
For i = 0 To UBound(subDirs)
newdir = subDirs(i)
fPath = makeDir(fPath, newdir)
Next i
End Sub
Then replace this:
MkDir ("T:\Estimating\William Cox Project Enquiries 2018\" & fPath)
If Err.Number <> 0 Then
Err.Clear
End If
With this:
makePath "T:\Estimating\William Cox Project Enquiries 2018\", fpath
You should also remove On Error Resume Next so that you can catch any other errors - Another of which might be in your path (per the screenshot) which has "T:\Estimating" twice at the beginning.

Rename File on Different Drive Using VBA

I have a list of file names in a worksheet. I want to read a name, find the actual file, rename it and move on to the next name.
The 1st part, retrieving the name from the worksheet and modifying it to the new name is not a problem. The problem is assigning the new name to the file.
The Name function does not work because the files are on a different drive. I also tried Scripting.FileSystemObject.
The code runs but no change is made.
Here is the code I used...
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set f = fso.GetFile(fOldName)
If Not Err = 53 Then 'File not found
'Rename file
f.Name = fNewName
End If
Did I make a code mistake I'm not seeing? Should I be using/doing something else?
Finding info on VBA and/or VB6 is getting pretty rare these days.
BTW. This is for Excel 2016.
Tks
If there was no misunderstanding...
FSO... it's bad in any case. It's just a bugsful API wrapper, written with a left chicken paw.
There are pure VB & API for more sophisticated cases.
No external libs & objects:
Public Sub sp_PrjFilMov()
Dim i As Byte
Dim sNam$, sExt$, sPthSrc$, sPthTgt$, sDir$
sPthSrc = "V:\"
sPthTgt = "R:\"
sNam = "Empty_"
sExt = ".dmy" ' dummy
For i = 1 To 5 ' create set of files for test
Call sx_CrtFil(i, sPthSrc, sNam, sExt)
Next
sDir = Dir(sPthSrc & "*" & sExt, vbNormal) ' lookup for our files ..
Do
'Debug.Print sDir
Select Case LenB(sDir)
Case 0
Exit Do ' *** EXIT DO
Case Else
Call sx_MovFil(sPthSrc, sDir, sPthTgt) ' .. & move them to another disk
sDir = Dir
End Select
Loop
Stop
End Sub
Private Sub sx_CrtFil(pNmb As Byte, pPth$, pNam$, pExt$)
Dim iFilNmb%
Dim sFilNam$
sFilNam = pPth & pNam & CStr(pNmb) & pExt
iFilNmb = FreeFile
Open sFilNam For Output As #iFilNmb
Close #iFilNmb
End Sub
Private Sub sx_MovFil(pPnmSrc$, pFnm$, pPthTgt$)
Dim sSrcPne$
sSrcPne = pPnmSrc & pFnm
'Debug.Print "Move " & sSrcPne & " --> " & pPthTgt
Call FileCopy(sSrcPne, pPthTgt & pFnm)
Call Kill(sSrcPne)
End Sub
'

Excel VBA - Code to open MS Project File not working

I wrote some code to allow me to select an MS Project file and open it, however when I run the code, nothing happens.
Zero errors, it just exits, any suggestions with what i'm doing wrong here?
Code below
Sub START()
' MS Project variables
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
'File Name Variables
Dim FileOpenType As Variant
Dim NewProjFileName As String
Dim NewProjFilePath As String
Dim NewProjFinal As String
'Code to find and open project files
Set Proj = CreateObject("MsProject.Application")
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
MsgBox ("You Havent Selected a File")
GoTo EndPoint
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
'Open Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
EndPoint:
End Sub
Just a couple of notes:
First, since you are using Early Binding to refer to MS-Project, so instead of setting Set Proj = CreateObject("MsProject.Application"), which is used for Late Binding, you can use Set Proj = New MSProject.Application.
Second: since Proj is defined as MSProject.Application, in order to make the MS-Project application visible, it's enough to use Proj.Visible = True.
Code
Option Explicit
Sub START()
' MS Project variables
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
'File Name Variables
Dim FileOpenType As Variant
Dim NewProjFileName As String
Dim NewProjFilePath As String
Dim NewProjFinal As String
Set Proj = New MSProject.Application ' since you are using Early binding, you can use this type of setting a new MS-Project instance
MsgBox "Please Select MS Project File for Quality Checking"
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
If FileOpenType = False Then
MsgBox "You Havent Selected a File"
Exit Sub ' <-- use Exit Sub instead of GoTo EndPoint
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
'Open Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
Proj.Visible = True ' <-- Set MS-Project as visible application
End Sub
Resolved by adding the following line, edited code to show
Proj.Application.Visible = True

how to return a value of variable from one module to another?

1st module..
Public Sub Directory_Path()
Dim Directory As String
Directory = InputBox("Enter the Directory path that contains folders ""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
If Right(Directory, 1) = "\" Then
Directory = Left(Directory, Len(Directory) - 1)
End If
End Sub
I called the the first module in 2nd module using Public Sub Directory_Path() . I want Directory variable in first module to be used as a variable in 2nd module... Help me. I miss something... If this question is repeated, please answer me and I will delete this post.
The most obvious solution is to just make it a function...
Public Function Directory_Path() As sting
Dim Directory As String
Directory = InputBox("Enter the Directory path that contains folders " & _
"""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
If Right(Directory, 1) = "\" Then
Directory_Path = Left(Directory, Len(Directory) - 1)
Else
Directory_Path = vbNullString
End If
End Function
...and then call the function:
Debug.Print Directory_Path
Note that instead of requiring the user to type the path, you can use the FileDialog instead:
Public Function Directory_Path() As String
Dim prompt As FileDialog
Set prompt = Application.FileDialog(msoFileDialogFolderPicker)
With prompt
.Title = "Select Directory path that contains folders " & _
"""This Quarter"",""Last Quarter"",""Second_Last_Quarter""."
.AllowMultiSelect = False
If .Show <> 0 Then Directory_Path = .SelectedItems(1)
End With
End Function