폴더를 만들고 폴더의 하위 폴더에서 Excel VBA

나는 풀 다운 메뉴의 회사에 의해 채워진 목록에서 다른 장이다. 세 개의 열이 있는 회사로,작업#고할 수 있습니다.

할 때 작업을 만들 필요에 대한 폴더는 회사와 하위 폴더에 대한 말할 수 있습니다.

는 경우에 당신은 경로를 아래로 이동처럼 보일 것입니다:

C:\Images\Company 이름\부품 번호\

는 경우 또는 회사 이름 또는 부품 번호 존재하지 않는't 만들고,또는 덮어쓰기 오래된 하나입니다. 그 다음 단계로 이동합니다. 그렇다면 모두 폴더가 아무것도 발생하는 경우,하나 또는 두지 않't 존재로 만들 필요합니다.

다른 질문은 거기에 그렇게 만들 수 있는 방법대로 작동하 Mac 및 Pc 를 같습니까?

질문에 대한 의견 (16)

또 다른 간단한 버전에서 작업하 PC:

Sub CreateDir(strPath As String)
    Dim elm As Variant
    Dim strCheckPath As String

    strCheckPath = ""
    For Each elm In Split(strPath, "\")
        strCheckPath = strCheckPath & elm & "\"
        If Len(Dir(strCheckPath, vbDirectory)) = 0 Then MkDir strCheckPath
    Next
End Sub
해설 (2)
해결책

하위와 두 가지 기능이 있습니다. 서브 구축 경로를 사용하여 기능을 확인하는 경로가 존재하고 만들지 않는 경우. 전체 경로가 존재한다는 그것이 전달합니다. 이 작업에는 PC,하지만 당신은 무엇인지 확인을 수정해야에서 작동하 Mac 니다.

'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()

Dim strComp As String, strPart As String, strPath As String

strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:\Images\"

If Not FolderExists(strPath & strComp) Then 
'company doesn't exist, so create full path
    FolderCreate strPath & strComp & "\" & strPart
Else
'company does exist, but does part folder
    If Not FolderExists(strPath & strComp & "\" & strPart) Then
        FolderCreate strPath & strComp & "\" & strPart
    End If
End If

End Sub

Function FolderCreate(ByVal path As String) As Boolean

FolderCreate = True
Dim fso As New FileSystemObject

If Functions.FolderExists(path) Then
    Exit Function
Else
    On Error GoTo DeadInTheWater
    fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
    Exit Function
End If

DeadInTheWater:
    MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
    FolderCreate = False
    Exit Function

End Function

Function FolderExists(ByVal path As String) As Boolean

FolderExists = False
Dim fso As New FileSystemObject

If fso.FolderExists(path) Then FolderExists = True

End Function

Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters

    CleanName = Replace(strName, "/","")
    CleanName = Replace(CleanName, "*","")
    etc...

End Function
해설 (16)

내가 찾은 훨씬 더 좋은 방법이고,적은 코드,더 많은 효율적이다. 참고는""""을 인용하는 경로로는 경우에 공백이 있을에서 폴더 이름입니다. 명령행 mkdir 만듭니다 어떤 중개 폴더에 필요한 경우 전체 경로가 존재합니다.

If Dir(YourPath, vbDirectory) = "" Then
    Shell ("cmd /c mkdir """ & YourPath & """")
End If
해설 (2)
Private Sub CommandButton1_Click()
    Dim fso As Object
    Dim tdate As Date
    Dim fldrname As String
    Dim fldrpath As String

    tdate = Now()
    Set fso = CreateObject("scripting.filesystemobject")
    fldrname = Format(tdate, "dd-mm-yyyy")
    fldrpath = "C:\Users\username\Desktop\FSO\" & fldrname
    If Not fso.folderexists(fldrpath) Then
        fso.createfolder (fldrpath)
    End If
End Sub
해설 (0)

거기에 몇 가지 좋은 대답을 여기에서,그래서 나는 그냥 몇 가지를 추가 프로세스 개선. 의 더 나은 방법을 결정하는 폴더가 존재할 경우(이용하지 않 FileSystemObjects 는 모든 컴퓨터가 사용하도록 허용하):

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err  0 Then FolderExists = False
     On Error GoTo 0
End Function

마찬가지로,

Function FileExists(FileName As String) As Boolean
     If Dir(FileName)  "" Then FileExists = True Else FileExists = False
EndFunction
해설 (0)

이처럼 작동하는 곳에서 AutoCad VBA 와 나에서 그것을 잡고 excel 포럼도 있습니다. I don't 왜 모두들 그렇게 복잡하게 하는가?

자주 묻는 질문

질문:'하는지 확인하는 특정 디렉토리가 존재한다. 지 않는 경우't 존재,나는'd 만들은 그것을 사용하여 VBA 코드입니다. 이렇게 하려면 어떻게 해야 합니까?

Answer:을 테스트할 수 있습니다면 디렉토리가 존재하는지를 이용 VBA 아래 코드:

(따옴표는 아래에 있는 생략의 혼동을 피하기 위해 프로그래밍 코드)


If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then

   MkDir "c:\TOTN\Excel\Examples"

End If

http://www.techonthenet.com/excel/formulas/mkdir.php

해설 (0)
'requires reference to Microsoft Scripting Runtime
Function MkDir(ByVal strDir As String)
    Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FolderExists(strDir) Then
        ' create parent folder if not exist (recursive)
        MkDir (fso.GetParentFolderName(strDir))
        ' doesn't exist, so create the folder
        fso.CreateFolder strDir
    End If
End Function
해설 (2)

적도 아닌 윈도우 시스템은,하지만 여기는's 나 내 라이브러리에있는,사용하기 매우 쉽습니다. 특별한 라이브러리를 참조 필요합니다.

Function CreateFolder(ByVal sPath As String) As Boolean
'by Patrick Honorez - www.idevlop.com
'create full sPath at once, if required
'returns False if folder does not exist and could NOT be created, True otherwise
'sample usage: If CreateFolder("C:\toto\test\test") Then debug.print "OK"
'updated 20130422 to handle UNC paths correctly ("\\MyServer\MyShare\MyFolder")

    Dim fs As Object 
    Dim FolderArray
    Dim Folder As String, i As Integer, sShare As String

    If Right(sPath, 1) = "\" Then sPath = Left(sPath, Len(sPath) - 1)
    Set fs = CreateObject("Scripting.FileSystemObject")
    'UNC path ? change 3 "\" into 3 "@"
    If sPath Like "\\*\*" Then
        sPath = Replace(sPath, "\", "@", 1, 3)
    End If
    'now split
    FolderArray = Split(sPath, "\")
    'then set back the @ into \ in item 0 of array
    FolderArray(0) = Replace(FolderArray(0), "@", "\", 1, 3)
    On Error GoTo hell
    'start from root to end, creating what needs to be
    For i = 0 To UBound(FolderArray) Step 1
        Folder = Folder & FolderArray(i) & "\"
        If Not fs.FolderExists(Folder) Then
            fs.CreateFolder (Folder)
        End If
    Next
    CreateFolder = True
hell:
End Function
해설 (0)

여기's 짧은 하지 않고 오류 처리를 생성하는 하위 디렉토리

Public Function CreateSubDirs(ByVal vstrPath As String)
   Dim marrPath() As String
   Dim mint As Integer

   marrPath = Split(vstrPath, "\")
   vstrPath = marrPath(0) & "\"

   For mint = 1 To UBound(marrPath) 'walk down directory tree until not exists
      If (Dir(vstrPath, vbDirectory) = "") Then Exit For
      vstrPath = vstrPath & marrPath(mint) & "\"
   Next mint

   MkDir vstrPath

   For mint = mint To UBound(marrPath) 'create directories
      vstrPath = vstrPath & marrPath(mint) & "\"
      MkDir vstrPath
   Next mint
End Function
해설 (0)

내가 이것을 알고 대답했고 많은 좋은 답변이 이미 하지만 사람들은 여기 와서 보면에 대한 솔루션을출할 수 있습니다 내가 무엇을 정착했으니다.

다음 코드를 모두 처리한 경로를 드라이브(다음과 같"C:\Users...")및 서버 주소(일:"\Server\경로는.."),걸리는 경로를 인수하고 자동으로 스트립의 모든 파일 이름에서 그것은(사"\"면 끝에 그's 는 이미 디렉토리 경로)그리고 그것은 경우 false 를 반환을 위한 어떤 이유 폴더를 만들 수 없습니다. 네,그것은 또한 만듭 sub-sub-sub-directories 는 경우,이를 요청합니다.

Public Function CreatePathTo(path As String) As Boolean

Dim sect() As String    ' path sections
Dim reserve As Integer  ' number of path sections that should be left untouched
Dim cPath As String     ' temp path
Dim pos As Integer      ' position in path
Dim lastDir As Integer  ' the last valid path length
Dim i As Integer        ' loop var

' unless it all works fine, assume it didn't work:
CreatePathTo = False

' trim any file name and the trailing path separator at the end:
path = Left(path, InStrRev(path, Application.PathSeparator) - 1)

' split the path into directory names
sect = Split(path, "\")

' what kind of path is it?
If (UBound(sect) < 2) Then ' illegal path
    Exit Function
ElseIf (InStr(sect(0), ":") = 2) Then
    reserve = 0 ' only drive name is reserved
ElseIf (sect(0) = vbNullString) And (sect(1) = vbNullString) Then
    reserve = 2 ' server-path - reserve "\\Server\"
Else ' unknown type
    Exit Function
End If

' check backwards from where the path is missing:
lastDir = -1
For pos = UBound(sect) To reserve Step -1

    ' build the path:
    cPath = vbNullString
    For i = 0 To pos
        cPath = cPath & sect(i) & Application.PathSeparator
    Next ' i

    ' check if this path exists:
    If (Dir(cPath, vbDirectory)  vbNullString) Then
        lastDir = pos
        Exit For
    End If

Next ' pos

' create subdirectories from that point onwards:
On Error GoTo Error01
For pos = lastDir + 1 To UBound(sect)

    ' build the path:
    cPath = vbNullString
    For i = 0 To pos
        cPath = cPath & sect(i) & Application.PathSeparator
    Next ' i

    ' create the directory:
    MkDir cPath

Next ' pos

CreatePathTo = True
Exit Function

Error01:

End Function

난 누군가를 찾을 수 있습니다 유용합니다. 을 즐길! :-)

해설 (0)

이것은 버전을 재귀와 함께 작동하는 드라이브 문자뿐만 아니라 UNC. 내가 사용하는 오류를 잡는 그것을 구현하지만 누구나 할 수 있다면 하나 없이,내가 관심을 가질 것입니다 그것을 참조하십시오. 이 방법은 가지에서 루트 할 수 있도록 다 쓸모 있는 경우 don't 에서 권한이 있는 루트와 낮은 부품의 디렉토리 나무입니다.

' Reverse create directory path. This will create the directory tree from the top    down to the root.
' Useful when working on network drives where you may not have access to the directories close to the root
Sub RevCreateDir(strCheckPath As String)
    On Error GoTo goUpOneDir:
    If Len(Dir(strCheckPath, vbDirectory)) = 0 And Len(strCheckPath) > 2 Then
        MkDir strCheckPath
    End If
    Exit Sub
' Only go up the tree if error code Path not found (76).
goUpOneDir:
    If Err.Number = 76 Then
        Call RevCreateDir(Left(strCheckPath, InStrRev(strCheckPath, "\") - 1))
        Call RevCreateDir(strCheckPath)
    End If
End Sub
해설 (0)
        Sub MakeAllPath(ByVal PS$)
Dim PP$
If PS  "" Then
    ' chop any end  name
    PP = Left(PS, InStrRev(PS, "\") - 1)
    ' if not there so build it
    If Dir(PP, vbDirectory) = "" Then
        MakeAllPath Left(PP, InStrRev(PS, "\") - 1)
        ' if not back to drive then  build on what is there
        If Right(PP, 1)  ":" Then MkDir PP
    End If
End If

End Sub

'마틴 루프 버전을 위에 보다 더 나은 내 재귀 버전 '그래서 아래를 향상

Sub MakeAllDir(경$)

'형식"K:\firstfold\secf\fold3"

는 경우 Dir(경로)=vbNullString 다음

'다른 사람을 귀찮게 하지 않습

Dim 리&,MYPath$,BuildPath$,PathStrArray$()

PathStrArray=Split(경로,"\")

  BuildPath = PathStrArray(0) & "\"    '

  If Dir(BuildPath) = vbNullString Then 

'트랩 문제의 드라이브 없음:\경로 주어

     If vbYes = MsgBox(PathStrArray(0) & "< not there for >" & PathS & " try to append to " & CurDir, vbYesNo) Then
        BuildPath = CurDir & "\"
     Else
        Exit Sub
     End If
  End If
  '
  ' loop through required folders
  '
  For LI = 1 To UBound(PathStrArray)
     BuildPath = BuildPath & PathStrArray(LI) & "\"
     If Dir(BuildPath, vbDirectory) = vbNullString Then MkDir BuildPath
  Next LI

최종 경우

'가

End Sub

'처럼 사용 'MakeAllDir"K:\bil\joan\Johno"

'MakeAllDir"K:\bil\joan\Fredso"

'MakeAllDir"K:\bil\tom\wattom"

'MakeAllDir"K:\bil\herb\watherb"

'MakeAllDir"K:\bil\herb\Jim"

'MakeAllDir"bil\안\왓"'기본 드라이브

해설 (0)