I would like to create the folder tree in VBA Excel based on the variables, which will be the UK postcodes.
https://en.wikipedia.org/wiki/List_of_postcode_areas_in_the_United_Kingdom
So, the first folder should be like shown below:
I would like to have the main folder with the major postcode city and some subfolders with the towns falling under this particular postcode city inside.
My piece of code looks like this:
Dim PCode as range
Dim BPcode As String, GPcode As String, PCity As String
Dim SelectedRow As Long
Dim PathName As String
Dim folderName As String, folderNameFull As String, subfolderName As String, fileName As String
Dim FinalPath As String
Set Target = ActiveCell
SelectedRow = Target.Row
Set WAddress = cstws.Range("K" & SelectedRow)
Set City = cstws.Range("L" & SelectedRow)
Set PCode = cstws.Range("M" & SelectedRow)
BPcode = Split(PCode, " ")(0)
GPcode = Remove_Number(BPcode)
Select Case GPcode
Case "NN"
PCity = "Northampton"
End Select
PathName = GetLocalPath(ThisWorkbook.path) & "\"
folderName = RemoveForbiddenFilenameChars(UCase(PCity))
folderNameFull = folderName & " [" & GPcode & "]"
subfolderName = RemoveForbiddenFilenameChars(UCase(City))
fileName = RemoveForbiddenFilenameChars(WAddress)
If subfolderName = "" Then MsgBox "What is the Site Address City?", vbCritical: Exit Sub
If fileName = "" Then MsgBox "Address incorrect or not provided", vbCritical: Exit Sub
If Dir(PathName & folderNameFull, vbDirectory) = "" Then
MkDir PathName & folderNameFull
Else
MsgBox "The Folder " & folderNameFull & " already exists"
End If
If Dir(PathName & folderNameFull & subfolderName, vbDirectory) = "" Then
MkDir PathName & folderNameFull & subfolderName
Else
MsgBox "The Folder " & subfolderName & " already exists"
End If
Function RemoveForbiddenFilenameChars(ByVal fileName As String) As String
Const forbiddenChars As String = "\/:*?""<>|[]" '[ and ] are excel specific
Dim i As Long, j As Long
Dim currChar As String
j = 0
For i = 1 To Len(fileName)
currChar = Mid(fileName, i, 1)
If InStr(forbiddenChars, currChar) = 0 And (AscW(currChar) > 31) Then
j = j + 1
Mid(fileName, j, 1) = currChar
End If
Next i
RemoveForbiddenFilenameChars = Left(fileName, j)
End Function
Function Remove_Number(Text As String) As String
With CreateObject("VBScript.RegExp")
.Global = True
.Pattern = "[0-9]"
Remove_Number = .Replace(Text, "")
End With
End Function
The functions used in this code can be found here:
VBA Excel - problem with saving file on newly created folder
As a result my folder tree is wrong. I neither have the correct name for the main folder, nor the subfolder placed inside.
The other solutions:
Create folders and subfolders based on two variables Creating Automatic Folders based on excel list Excel vba: creating folders doesn't work How to create folders using Excel VBA?
didn't work so far.
How could I create the folder tree in VBA Excel based on 2 values?