代码制作文件夹在空单元格值上显示错误

时间:2019-03-18 08:52:06

标签: vba directory

我设计了一个代码,用于根据单元格值创建文件夹,但是其中Excel电子表格包含公式。如果此时的单元格值为空,请停止该过程。

Sub MakeFolders()

    Dim xdir As String
    Dim FSO
    Dim lstrow As Long
    Dim i As Long

    Set FSO = CreateObject("Scripting.FileSystemObject")
    lstrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
    Application.ScreenUpdating = False
    For i = 2 To lstrow
        'change the path on the next line where you want to create the folders
        xdir = Range("E" & i).Value & Range("B" & i).Value
        If Not FSO.FolderExists(xdir) Then
               FSO.CreateFolder (xdir)
        End If
    Next
    Application.ScreenUpdating = True
    MsgBox "Folder Created Successfully", vbInformation, "Info"

End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

这应该绕过您的错误:

Sub MakeFolders()
    Dim xdir As String
    Dim FSO
    Dim lstrow As Long
    Dim i As Long

    Set FSO = CreateObject("Scripting.FileSystemObject")
    lstrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
    Application.ScreenUpdating = False
    For i = 2 To lstrow
        'change the path on the next line where you want to create the folders
        xdir = Range("E" & i).Value & Range("B" & i).Value
        If Not xdir = vbNullString And Not FSO.FolderExists(xdir) Then 'I've added here a check for the xdir value, if it's empty it won't try to create the folder.
            FSO.CreateFolder (xdir)
        End If
    Next
    Application.ScreenUpdating = True
    MsgBox "Folder Created Successfully", vbInformation, "Info"

End Sub