我正在开发一个基本上将文件夹和文件从服务器复制到本地计算机的脚本。在研究这个时,我发现我需要某种类型的函数,它基本上需要一个完整的文件夹路径字符串,将其拆分并检查每个文件夹是否存在。如果没有,请创建该文件夹。
所以,我正在考虑一种聪明的方法,以便我可以在以后重用代码。 我希望它采用一个参数,即完整路径的字符串。代码完成其余的工作。
编辑:这是Jean-FrançoisCorbett完成的代码。我会给你9000多谢谢你!
Public Sub createFolderStructure(ByVal strFullPath)
Set objFSO = CreateObject("Scripting.FileSystemObject")
' How many levels are there?
nLevel = 0
strParentPath = strFullPath
Do Until strParentPath = ""
strParentPath = objFSO.GetParentFolderName(strParentPath)
nLevel = nLevel + 1
Loop
For iLevel = 1 To nLevel
' Figure out path for directory at level iLevel
strParentPath = strFullPath
For j = 1 To nLevel - iLevel
strParentPath = objFSO.GetParentFolderName(strParentPath)
Next
' Does this directory exist? If not, create it.
If objFSO.FolderExists(strParentPath) = False Then
Set newFolder = objFSO.CreateFolder(strParentPath)
End If
Next
End Sub
答案 0 :(得分:1)
既然您已经objFSO
了,为什么不使用GetParentFolderName
和FolderExists
方法。真的,FileSystemObject
已经解决了大部分问题,所以不必担心一些痛苦;无需重新发明轮子。
编辑:以下是我认为您想要做的一个示例。根据您的需要进行调整。
strFullPath = "C:\aaaa\Test\Vbscript" ' 4 levels
' How many levels are there?
nLevel = 0
strParentPath = strFullPath
Do Until strParentPath = ""
strParentPath = FSO.GetParentFolderName(strParentPath)
nLevel = nLevel + 1
Loop
Debug.Print nLevel ' nLevel = 4 for this example
For iLevel = 1 To nLevel
' Figure out path for directory at level iLevel
strParentPath = strFullPath
For j = 1 To nLevel - iLevel
strParentPath = FSO.GetParentFolderName(strParentPath)
Next j
' Does this directory exist? If not, create it.
Debug.Print iLevel, strParentPath, FSO.FolderExists(strParentPath)
If FSO.FolderExists(strParentPath) = False Then
Set newFolder = FSO.CreateFolder(strParentPath)
End If
Next iLevel