今天修改了一个包含VBA代码的Excel文件,其中包含创建文件夹的功能,却始终无法成功执行。
排查后发现使用的是MkDir方法,但这个方法是有局限的,MkDir一次只能创建一个目录,并且无法创建子目录。
因此,如果想要创建类似“D:\TestA\TestB”这样的目录,就必须执行两次MkDir。
MkDir "D:\TestA" MkDir "D:\TestA\TestB"
如果在“D:\TestA”不存在的情况下,直接执行下述代码,是会报错的。
MkDir "D:\TestA\TestB"
以下是在网上找到并测试有效的方法:
方法一:
Private Declare PtrSafe Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal lpPath As String) As Long Public Sub MakeFullDir(strPath As String) If Right(strPath, 1) <> "\" Then strPath = strPath & "\" 'Optional depending upon intent MakeSureDirectoryPathExists strPath End Sub
方法二:
Public Sub MyMkDir(sPath As String) Dim iStart As Integer Dim aDirs As Variant Dim sCurDir As String Dim i As Integer If sPath <> "" Then aDirs = Split(sPath, "\") If Left(sPath, 2) = "\\" Then iStart = 3 Else iStart = 1 End If sCurDir = Left(sPath, InStr(iStart, sPath, "\")) For i = iStart To UBound(aDirs) sCurDir = sCurDir & aDirs(i) & "\" If Dir(sCurDir, vbDirectory) = vbNullString Then MkDir sCurDir End If Next i End If End Sub