VBA 文本文件

读取Excel文件,并使用VBA将单元格的内容写入文本文件。VBA允许用户使用两种方法处理文本文件 -

  • 文件系统对象(FSO)
  • 使用Write命令

VBA 文本文件_第1张图片

Drive

Drive 是一个对象,它提供对特定磁盘驱动器或网络共享的属性的访问。 Drive对象支持以下属性 -

  • AvailableSpace
  • DriveLetter
  • DriveType
  • FileSystem
  • FreeSpace
  • IsReady
  • Path
  • RootFolder
  • SerialNumber
  • ShareName
  • TotalSize
  • VolumeName

示例:

Sub CommandButton1_Click()
   Const ForReading = 1, ForWriting = 2, ForAppending = 3
   Dim FilePath As String
   Dim CellData As String
   Dim LastCol As Long
   Dim LastRow As Long
   LastCol = ActiveSheet.UsedRange.Columns.Count
   LastRow = ActiveSheet.UsedRange.Rows.Count

    ' Create a TextStream.
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set stream = fso.OpenTextFile("D:\vba\Support.log", ForWriting, True)

   CellData = ""
   ' LastRow = 3
   LastCol = 3
   For i = 1 To LastRow
      For j = 1 To LastCol
         CellData = Trim(ActiveCell(i, j).Value)
         stream.WriteLine "The Value at location (" & i & "," & j & ")" & CellData
      Next j
   Next i

   stream.Close
   MsgBox ("Job Done")

End Sub

 

VBA 文本文件_第2张图片

 

Write命令

与FSO不同,不需要添加任何引用,但是,我们将无法使用驱动器,文件和文件夹。也能够将流添加到文本文件。

Sub CommandButton1_Click()
   Const ForReading = 1, ForWriting = 2, ForAppending = 3
   Dim FilePath As String
   Dim CellData As String
   Dim LastCol As Long
   Dim LastRow As Long

   LastCol = ActiveSheet.UsedRange.Columns.Count
   LastRow = ActiveSheet.UsedRange.Rows.Count

   FilePath = "F:\worksp\vba\write.txt"
   Open FilePath For Output As #2

   CellData = ""
   LastCol = 3
   For i = 1 To LastRow
      For j = 1 To LastCol
         CellData = "The Value at location (" & i & "," & j & ")" & Trim(ActiveCell(i, j).Value)
         Write #2, CellData
      Next j
   Next i

   Close #2
   MsgBox ("Job Done")

End Sub

 

VBA 文本文件_第3张图片

VBA 文本文件_第4张图片

 

 

 

 

你可能感兴趣的:(VBA)