수색…


FileSystemObject 만들기

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Sub FsoExample()
    Dim fso As Object ' declare variable
    Set fso = CreateObject("Scripting.FileSystemObject") ' Set it to be a File System Object

    ' now use it to check if a file exists
    Dim myFilePath As String
    myFilePath = "C:\mypath\to\myfile.txt"
    If fso.FileExists(myFilePath) Then
        ' do something
    Else
        ' file doesn't exist
        MsgBox "File doesn't exist"
    End If
End Sub

FileSystemObject를 사용하여 텍스트 파일 읽기

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Sub ReadTextFileExample()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim sourceFile As Object
    Dim myFilePath As String
    Dim myFileText As String

    myFilePath = "C:\mypath\to\myfile.txt"
    Set sourceFile = fso.OpenTextFile(myFilePath, ForReading)
    myFileText = sourceFile.ReadAll ' myFileText now contains the content of the text file
    sourceFile.Close ' close the file
    ' do whatever you might need to do with the text

    ' You can also read it line by line
    Dim line As String
    Set sourceFile = fso.OpenTextFile(myFilePath, ForReading)
    While Not sourceFile.AtEndOfStream ' while we are not finished reading through the file
        line = sourceFile.ReadLine
        ' do something with the line...
    Wend
    sourceFile.Close
End Sub

FileSystemObject를 사용하여 텍스트 파일 만들기

Sub CreateTextFileExample()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim targetFile As Object
    Dim myFilePath As String
    Dim myFileText As String

    myFilePath = "C:\mypath\to\myfile.txt"
    Set targetFile = fso.CreateTextFile(myFilePath, True)  ' this will overwrite any existing file
    targetFile.Write "This is some new text"
    targetFile.Write " And this text will appear right after the first bit of text."
    targetFile.WriteLine "This bit of text includes a newline character to ensure each write takes its own line."
    targetFile.Close ' close the file
End Sub

FileSystemObject를 사용하여 기존 파일에 쓰기

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8


Sub WriteTextFileExample()
    Dim oFso
    Set oFso = CreateObject("Scripting.FileSystemObject")

    Dim oFile as Object
    Dim myFilePath as String
    Dim myFileText as String

    myFilePath = "C:\mypath\to\myfile.txt"
    ' First check if the file exists
    If oFso.FileExists(myFilePath) Then
        ' this will overwrite any existing filecontent with whatever you send the file
        ' to append data to the end of an existing file, use ForAppending instead
        Set oFile = oFso.OpenTextFile(myFilePath, ForWriting)  
    Else
        ' create the file instead
        Set oFile = oFso.CreateTextFile(myFilePath) ' skipping the optional boolean for overwrite if exists as we already checked that the file doesn't exist.
    End If
    oFile.Write "This is some new text"
    oFile.Write " And this text will appear right after the first bit of text."
    oFile.WriteLine "This bit of text includes a newline character to ensure each write takes its own line."
    oFile.Close ' close the file
End Sub

FileSystemObject를 사용하여 디렉터리의 파일 열거

초기 바인딩 (Microsoft Scripting Runtime 참조 필요) :

Public Sub EnumerateDirectory()
    Dim fso As Scripting.FileSystemObject
    Set fso = New Scripting.FileSystemObject

    Dim targetFolder As Folder
    Set targetFolder = fso.GetFolder("C:\")
    
    Dim foundFile As Variant
    For Each foundFile In targetFolder.Files
        Debug.Print foundFile.Name
    Next
End Sub

후기 :

Public Sub EnumerateDirectory()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim targetFolder As Object
    Set targetFolder = fso.GetFolder("C:\")
    
    Dim foundFile As Variant
    For Each foundFile In targetFolder.Files
        Debug.Print foundFile.Name
    Next
End Sub

폴더와 파일을 재귀 적으로 열거합니다.

Early Bound ( Microsoft Scripting Runtime 참조)

Sub EnumerateFilesAndFolders( _
    FolderPath As String, _
    Optional MaxDepth As Long = -1, _
    Optional CurrentDepth As Long = 0, _
    Optional Indentation As Long = 2)
  
    Dim FSO As Scripting.FileSystemObject
    Set FSO = New Scripting.FileSystemObject
    
    'Check the folder exists
    If FSO.FolderExists(FolderPath) Then
        Dim fldr As Scripting.Folder
        Set fldr = FSO.GetFolder(FolderPath)
        
        'Output the starting directory path
        If CurrentDepth = 0 Then
          Debug.Print fldr.Path
        End If
        
        'Enumerate the subfolders
        Dim subFldr As Scripting.Folder
        For Each subFldr In fldr.SubFolders
            Debug.Print Space$((CurrentDepth + 1) * Indentation) & subFldr.Name
            If CurrentDepth < MaxDepth Or MaxDepth = -1 Then
                'Recursively call EnumerateFilesAndFolders
                EnumerateFilesAndFolders subFldr.Path, MaxDepth, CurrentDepth + 1, Indentation
            End If
        Next subFldr
        
        'Enumerate the files
        Dim fil As Scripting.File
        For Each fil In fldr.Files
            Debug.Print Space$((CurrentDepth + 1) * Indentation) & fil.Name
        Next fil
    End If
End Sub

인수를 사용하여 호출하면 출력 : EnumerateFilesAndFolders "C:\Test"

C:\Test
  Documents
    Personal
      Budget.xls
      Recipes.doc
    Work
      Planning.doc
  Downloads
    FooBar.exe
  ReadMe.txt

다음과 같은 인수를 사용하여 호출하면 출력 : EnumerateFilesAndFolders "C:\Test", 0

C:\Test
  Documents
  Downloads
  ReadMe.txt

다음과 같은 인수를 사용하여 호출하면 출력 : EnumerateFilesAndFolders "C:\Test", 1, 4

C:\Test
    Documents
        Personal
        Work
    Downloads
        FooBar.exe
    ReadMe.txt

파일 이름에서 파일 확장명 제거

Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName("MyFile.something.txt")

MyFile.something 인쇄 MyFile.something

GetBaseName() 메서드는 이미 파일 이름에서 여러 마침표를 처리합니다.

파일 이름에서 확장자 만 검색

Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetExtensionName("MyFile.something.txt")

Prints txt GetExtensionName() 메서드는 이미 파일 이름에서 여러 마침표를 처리합니다.

파일 경로에서 경로 만 검색

GetParentFolderName 메서드는 모든 경로의 부모 폴더를 반환합니다. 폴더와 함께 사용할 수도 있지만 절대 경로에서 경로를 추출하는 데 더 유용 할 수 있습니다.

Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetParentFolderName("C:\Users\Me\My Documents\SomeFile.txt")

C:\Users\Me\My Documents 인쇄합니다 C:\Users\Me\My Documents

후행 경로 구분 기호는 반환 된 문자열에 포함되지 않습니다.

FSO.BuildPath를 사용하여 폴더 경로 및 파일 이름에서 전체 경로 만들기

폴더 경로에 대한 사용자 입력을 수락하는 경우 파일 경로를 만들기 전에 백 슬래시 ( \ )가 있는지 확인해야합니다. FSO.BuildPath 메서드를 사용하면이 작업이보다 간단 해집니다.

  Const sourceFilePath As String = "C:\Temp"  '<-- Without trailing backslash
  Const targetFilePath As String = "C:\Temp\" '<-- With trailing backslash

  Const fileName As String = "Results.txt"
  
  Dim FSO As FileSystemObject
  Set FSO = New FileSystemObject
  
  Debug.Print FSO.BuildPath(sourceFilePath, fileName)
  Debug.Print FSO.BuildPath(targetFilePath, fileName)

산출:

C:\Temp\Results.txt
C:\Temp\Results.txt


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow