gpt4 book ai didi

excel - 尝试使用 VBA 从 excel 创建文件夹和子文件夹

转载 作者:行者123 更新时间:2023-12-04 22:30:09 25 4
gpt4 key购买 nike

我在 excel 中有两列数据,我试图将它们转换为文件夹和子文件夹列表。 A 列将是主文件夹的第一个列表,B 列的每个条目将是 A 列相应文件夹中的一个子文件夹。最终结果将是 20 个文件夹,每个文件夹里面都有一个文件夹。我以前使用过这个代码-

Sub MakeFolders()
Dim Rng As Range
Dim maxRows, maxCols, r, c As Integer
Set Rng = Selection
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count
For c = 1 To maxCols
r = 1
Do While r <= maxRows
If Len(Dir(ActiveWorkbook.Path & "\" & Rng(r, c), vbDirectory)) = 0 Then
MkDir (ActiveWorkbook.Path & "\" & Rng(r, c))
On Error Resume Next
End If
r = r + 1
Loop
Next c
End Sub

- 从单列数据创建单个文件夹的列表。我想知道如何更改该代码以创建包含第一列的文件夹列表,并使第二列中的每个条目成为 A 列相应文件夹中的子文件夹。 Excel 电子表格如下所示:
    Column A        Column B
1 Folder 1 Subfolder in Folder 1
2 Folder 2 Subfolder in Folder 2
3 Folder 3 Subfolder in Folder 3
4 Folder 4 Subfolder in Folder 4
5 Folder 5 Subfolder in Folder 5
6 Folder 6 Subfolder in Folder 6
7 Folder 7 Subfolder in Folder 7
8 Folder 8 Subfolder in Folder 8
9 Folder 9 Subfolder in Folder 9
10 Folder 10 Subfolder in Folder 10

由于我对 VBA 的了解非常有限,任何帮助都将不胜感激!

最佳答案

未经测试:

Sub MakeFolders()
Dim Rng As Range, rw As Range, c As Range
Dim p As String, v As String

Set Rng = Selection

'process each selected row
For Each rw In Rng.Rows
p = ActiveWorkbook.Path & "\" 'set initial root path for this row
'process each cell in this row
For Each c In rw.Cells
v = Trim(c.Value) 'what's in the cell?
If Len(v) > 0 Then
If Len(Dir(p & v, vbDirectory)) = 0 Then MkDir (p & v) 'create if not already there
p = p & v & "\" 'append to path (regardless of whether it needed to be created)
End If
Next c
Next rw

End Sub

关于excel - 尝试使用 VBA 从 excel 创建文件夹和子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53766750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com