itsource

VBA를 사용하여 폴더의 Excel 파일 목록 가져오기

mycopycode 2023. 5. 27. 11:08
반응형

VBA를 사용하여 폴더의 Excel 파일 목록 가져오기

저는 폴더에 있는 모든 엑셀 파일의 이름을 가져온 다음 각 파일을 변경해야 합니다.했습니다."변경" 부분을 정리했습니다.다음 목록을 얻을 수 있는 방법이 있습니까?.xlsx예를 들어, 한 폴더에 있는 파일D:\Personal문자열 배열에 저장합니다.

그런 다음 파일 목록을 반복하고 다음을 사용하여 각 파일에서 매크로를 실행해야 합니다.

Filepath = "D:\Personal\"
For Each i in FileArray
    Workbooks.Open(Filepath+i)
Next

저는 이것을 보았지만, 그것이 이름을 저장했기 때문에 파일을 열 수 없었습니다.Variant서식을 정하다

간단히 말해서, VBA를 사용하여 특정 폴더에 있는 Excel 파일 이름 목록을 가져오려면 어떻게 해야 합니까?

좋아요, 이것은 경로를 선택하고 폴더의 파일 이름 배열을 반환하는 기능인 당신에게 효과적일 수 있습니다.배열을 반복할 때 if 문을 사용하여 Excel 파일만 가져올 수 있습니다.

Function listfiles(ByVal sPath As String)

    Dim vaArray     As Variant
    Dim i           As Integer
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    Set oFiles = oFolder.Files

    If oFiles.Count = 0 Then Exit Function

    ReDim vaArray(1 To oFiles.Count)
    i = 1
    For Each oFile In oFiles
        vaArray(i) = oFile.Name
        i = i + 1
    Next

    listfiles = vaArray

End Function

인덱스 번호로 파일 개체의 파일에 액세스할 수 있으면 좋겠지만 어떤 이유로든 VBA에서 손상된 것 같습니다(버그?).

내장된 Dir 함수 또는 FileSystemObject를 사용할 수 있습니다.

그들은 각각 장단점을 가지고 있습니다.

디르 함수

Dir Function은 파일 목록을 가져올 수 있는 내장된 경량 방법입니다.사용 시 이점은 다음과 같습니다.

  • 사용하기 쉬운
  • 좋은 성능(빠름)
  • 와일드카드 지원

매개 변수를 사용하거나 사용하지 않고 호출하는 것의 차이를 이해하는 것이 요령입니다.다음은 매우 간단한 예입니다.

Public Sub ListFilesDir(ByVal sPath As String, Optional ByVal sFilter As String)

    Dim sFile As String

    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If

    If sFilter = "" Then
        sFilter = "*.*"
    End If

    'call with path "initializes" the dir function and returns the first file name
    sFile = Dir(sPath & sFilter)

   'call it again until there are no more files
    Do Until sFile = ""

        Debug.Print sFile

        'subsequent calls without param return next file name
        sFile = Dir

    Loop

End Sub

루프 내의 파일을 변경하면 예측할 수 없는 결과가 발생합니다.파일에 대한 작업을 수행하기 전에 모든 이름을 문자열 배열로 읽는 것이 좋습니다.다음은 이전 버전을 기반으로 하는 예제입니다.문자열 배열을 반환하는 함수입니다.

Public Function GetFilesDir(ByVal sPath As String, _
    Optional ByVal sFilter As String) As String()

    'dynamic array for names
    Dim aFileNames() As String
    ReDim aFileNames(0)

    Dim sFile As String
    Dim nCounter As Long

    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If

    If sFilter = "" Then
        sFilter = "*.*"
    End If

    'call with path "initializes" the dir function and returns the first file
    sFile = Dir(sPath & sFilter)

    'call it until there is no filename returned
    Do While sFile <> ""

        'store the file name in the array
        aFileNames(nCounter) = sFile

        'subsequent calls without param return next file
        sFile = Dir

        'make sure your array is large enough for another
        nCounter = nCounter + 1
        If nCounter > UBound(aFileNames) Then
            'preserve the values and grow by reasonable amount for performance
            ReDim Preserve aFileNames(UBound(aFileNames) + 255)
        End If

    Loop

    'truncate the array to correct size
    If nCounter < UBound(aFileNames) Then
        ReDim Preserve aFileNames(0 To nCounter - 1)
    End If

    'return the array of file names
    GetFilesDir = aFileNames()

End Function

파일 시스템 개체

파일 시스템 개체는 IO 작업을 위한 라이브러리로, 파일을 조작하기 위한 개체 모델을 지원합니다.이 접근 방식에 대한 장점:

  • 인텔리센스
  • 강력한 객체 모델

"Windows Script Host Object Model"(또는 "Windows Scripting Runtime")에 대한 참조를 추가하고 다음과 같이 개체를 선언할 수 있습니다.

Public Sub ListFilesFSO(ByVal sPath As String)

    Dim oFSO As FileSystemObject
    Dim oFolder As Folder
    Dim oFile As File

    Set oFSO = New FileSystemObject
    Set oFolder = oFSO.GetFolder(sPath)
    For Each oFile In oFolder.Files
        Debug.Print oFile.Name
    Next 'oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

End Sub

인텔리전트 라이센스를 원하지 않는 경우 참조를 설정하지 않고 다음과 같이 할 수 있습니다.

Public Sub ListFilesFSO(ByVal sPath As String)

    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    For Each oFile In oFolder.Files
        Debug.Print oFile.Name
    Next 'oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

End Sub
Dim iIndex as Integer
Dim ws As Excel.Worksheet
Dim wb      As Workbook
Dim strPath As String
Dim strFile As String

strPath = "D:\Personal\"
strFile = Dir(strPath & "*.xlsx")

Do While strFile <> ""
    Set wb = Workbooks.Open(Filename:=strPath & strFile)

    For iIndex = 1 To wb.Worksheets.count
        Set ws = wb.Worksheets(iIndex)

        'Do something here.

    Next iIndex

 strFile = Dir 'This moves the value of strFile to the next file.
Loop

파일 확장명이 없는 파일 이름만 원하는 경우

Dim fileNamesCol As New Collection
Dim MyFile As Variant  'Strings and primitive data types aren't allowed with collection

filePath = "c:\file directory" + "\"
MyFile = Dir$(filePath & "*.xlsx")
Do While MyFile <> ""
    fileNamesCol.Add (Replace(MyFile, ".xlsx", ""))
    MyFile = Dir$
Loop

Excel 워크시트로 출력하는 방법

Dim myWs As Worksheet: Set myWs = Sheets("SheetNameToDisplayTo")
Dim ic As Integer: ic = 1

For Each MyFile In fileNamesCol
    myWs.Range("A" & ic).Value = fileNamesCol(ic)
    ic = ic + 1
Next MyFile

주로 여기에 설명된 기술을 기반으로 합니다. https://wordmvp.com/FAQs/MacrosVBA/ReadFilesIntoArray.htm

업데이트된 답변과 관련하여, 결과적으로 "listfiles" 배열이 배열 수식 {CSE}에 사용되면 목록 값이 모두 수평 행으로 나온다는 점을 제외하고는 마음에 들었습니다.수직 열로 표시하기 위해 배열을 다음과 같이 2차원으로 만들었습니다.

ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
    vaArray(i, 0) = oFile.Name
    i = i + 1
Next
Sub test()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder1 = FSO.GetFolder(FromPath).Files
    FolderPath_1 = "D:\Arun\Macro Files\UK Marco\External Sales Tool for Au\Example Files\"
    Workbooks.Add
    Set Movenamelist = ActiveWorkbook
    For Each fil In folder1
        Movenamelist.Activate
        Range("A100000").End(xlUp).Offset(1, 0).Value = fil
        ActiveCell.Offset(1, 0).Select
    Next
End Sub

언급URL : https://stackoverflow.com/questions/31414106/get-list-of-excel-files-in-a-folder-using-vba

반응형