AccessVBA入門③FileSystemObject

Access

今回は、AccessVBAの便利な機能で、FileSystemObjectを紹介します。Microsoft Scripting Runtimeライブラリで、ドライブ・フォルダ・ファイルを操作できるようになります。

◉FileSystemObject

Sub Test1()
  Dim FSO As New FileSystemObject
  Dim MyPath As String
  MyPath = CurrentProject.Path & "¥"
  If Not FSO.FolderExists(MyPath & "test") Then
    FSO.CreateFolder MyPath & "test"
    MsgBox "「test」フォルダを作成しました"
  End If
  MyPath = MyPath & "test¥"
  If Not FSO.FileExists(MyPath & "01.txt") Then
    FSO.CreateTextFile MyPath & "01.txt"
    MsgBox "「01.txt」を作成しました"
    FSO.CopyFile MyPath & "01.txt", MyPath & "02.txt"
    FSO.CopyFile MyPath & "02.txt", MyPath & "03.txt"
    MsgBox "「01.txt」のコピー「02.03.txt」を作成しました"
  End If
  Set FSO = Nothing
End Sub

◉Drive

Sub Test2()
  Dim FSO As New FileSystemObject
  Dim MyDrive As Drive
  Set MyDrive = FSO.GetDrive("C")
  MsgBox "Cドライブの情報" & vbCrLf & _
         "準備は:" & MyDrive.IsReady & vbCrLf & _
         "パスは:" & MyDrive.Path & vbCrLf & _
         "タイプは:" & MyDrive.DriveType & vbCrLf & _
         "総容量は:" & MyDrive.TotalSize & vbCrLf & _
         "空容量は" & MyDrive.FreeSpace & vbCrLf & _
         "ファイルシステムは" & MyDrive.FileSystem
  Set FSO = Nothing
End Sub

◉Folder

◉File

Sub Test3()
  Dim FSO As New FileSystemObject
  Dim MyFolder As Folder
  Dim MyFile As File
  Dim MyPath As String
  Dim MyStr As String
  MyPath = CurrentProject.Path & "¥"
  Set MyFolder = FSO.GetFolder(MyPath & "test")
  For Each MyFile In MyFolder.Files
    MyStr = MyStr & MyFile.Name & vbCrLf
  Next MyFile
  MsgBox "「test」フォルダには" & vbCrLf & _
          MyStr & "のファイルが存在します"
  MsgBox "「test」フォルダは" & _
          MyFolder.DateCreated & "に作成されました"
  Set MyFolder = Nothing
  Set FSO = Nothing
End Sub

◉TextStream

Sub Test4()
  Dim FSO As New FileSystemObject
  Dim MyText As TextStream
  Dim MyPath As String
  MyPath = CurrentProject.Path & "¥test"

  Set MyText = FSO.OpenTextFile(MyPath & "¥01.txt", ForWriting)
  MyText.Write"12345"
  MyText.Write"67890"
  MyText.WriteBlankLines 1
  MyText.WriteLine "ABCDEFGHIJ"
  MyText.Close

  Set MyText = FSO.OpenTextFile(MyPath & "¥01.txt", ForReading)
  MsgBox MyText.ReadLine
  MsgBox MyText.Read(5)
  MyText.Close

  Set MyText = Nothing
  FSO.DeleteFolder MyPath
  Set FSO = Nothing
End Sub

コメント

タイトルとURLをコピーしました