使用依赖于单元格值的 VBA 创建文件夹目录



我有一个Excel电子表格,我用它来作为工作跟踪器。我想用 VBA 编写一个代码,该代码根据为每条记录输入的一些值创建一个目录(带有子文件夹(。

列 A:密码 B:团队 C:标题

在Windows中已经建立的目录中,我有一个文件夹,其中包含我们工作的所有团队的文件夹。基本上,我希望有代码,以便它在我的跟踪器中查看团队值,并在该团队区域中创建一个新文件夹(带有子文件夹(。

例如:"C:\团队\团队 1\新文件夹转到此处">

我希望创建的新文件夹使用A列和C列中的PIN +标题格式.另外,在每个新创建的文件夹中,我想要这些子文件夹:"1_Comms","2_Input","3_Working","4_Output"。

例如:"C:\Teams\Team 1\PIN 值 + 标题",其中包含此新目录中的所有上述子文件夹。

任何这方面的帮助将不胜感激,因为我是 VBA 的菜鸟,并且仍在学习。

到目前为止,除了完全让自己尴尬之外,还没有尝试过任何东西。

为此,您首先创建主文件夹,如示例中的"C:\Teams\Team 1\PIN value + Title"。因此,之后创建子文件夹。

Sub CreateFolder(ByVal pin_value As String, ByVal title As String)
Dim wb_path As String
Dim folder_1_path, folder_2_path, folder_3_path, folder_4_path As String
wb_path = ThisWorkbook.Path
' create main folder
wb_path = wb_path & "" & pin_value & "_" & title
MkDir (wb_path)
' create subfolder  
folder_1_path = wb_path & "1_Comms"
folder_2_path = wb_path & "2_Input"
folder_3_path = wb_path & "3_Working"
folder_4_path = wb_path & "4_Output"
MkDir (folder_1_path)
MkDir (folder_2_path)
MkDir (folder_3_path)
MkDir (folder_4_path)
End Sub

如果您的 PIN 码是整数,则需要将其转换为字符串。就像下面的测试一样:

Sub test()
pin_value = 777
title = "myFolder"
pin_value = CStr(pin_value)
Call CreateFolder(pin_value, title)
End Sub

您可以使用此递归函数,负责处理丢失的文件夹:

Function SmartCreateFolder(byVal sFolder as String) As Boolean
'inspired by: https://stackoverflow.com/a/54280512/78522
'Works with drive letters but also with UNC paths
Static oFSO As Object
If oFSO Is Nothing Then Set oFSO = CreateObject("Scripting.FileSystemObject")
On Error GoTo hell  'mostly to handle forbidden characters
With oFSO
If Not .FolderExists(sFolder) Then
If SmartCreateFolder(.GetParentFolderName(sFolder)) Then
.CreateFolder sFolder
Else
GoTo hell
End If
End If
End With
SmartCreateFolder = True
hell:
End Function

最新更新