我想用Excel创建文件夹,每次在所选列中创建新条目时,都会创建一个新文件夹。
我已经搜索并找到了一些创建文件夹的VBA代码。但是我必须选择单元格,然后每次都运行宏。有什么方法可以自动执行此操作吗?
提前谢谢你, 狮子座
下面是创建新文件夹(子目录)的代码
Sub CreateFolder()
Dim caminho As String
Dim folder As Object, FolderName
For i = 1 To 500
Set folder = CreateObject("Scripting.FileSystemObject") FolderName = ActiveWorkbook.Path & "" & Range("A" & i).Value
If Not folder.FolderExists(FolderName) Then
folder.CreateFolder (FolderName)
End If
directory = ThisWorkbook.Path
Next i
End Sub
是的,我们可以为您提供帮助。 只需要一些相关信息。 是否需要选择列? 或者您可以使用硬编码列吗? 假设像 D 列这样的列... 我们可以在您的工作表模块上放置一个Worksheet_Change宏,以便每当更改某个列中的值时 - 它将自动检查该文件夹是否存在,如果不存在,则创建它。
以下示例将为 D 列中的任何新单元格或更改的单元格创建文件夹:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim caminho As String
Dim folder As Object, FolderName
If Target.Column = 1 And Target.Value <> "" Then ' If Changed Cell is in Column A
' This code changes unacceptable file name characters with an underscore
Filename = Target.Value
MyArray = Array("<", ">", "|", "/", "*", "", "?", """")
For X = LBound(MyArray) To UBound(MyArray)
Filename = Replace(Filename, MyArray(X), "_", 1)
Next X
' This code creates the folder if it doesn't already exist
Set folder = CreateObject("Scripting.FileSystemObject")
FolderName = ActiveWorkbook.Path & "" & Filename
If Not folder.FolderExists(FolderName) Then
folder.CreateFolder (FolderName)
End If
End If
End Sub