還可以讀取Excel檔,並使用VBA將單元格的內容寫入文本檔。VBA允許用戶使用兩種方法處理文本檔 -
- 檔系統對象(
FSO
) - 使用
Write
命令
檔系統對象(FSO)
顧名思義,FSO
對象幫助開發人員使用驅動器,檔夾和文件。 在本節中,我們將討論如何使用FSO
。
編號 | 對象類型 | 描述 |
---|---|---|
1 | Drive |
Drive 是一個對象。 包含收集有關連接到系統的驅動器的資訊的方法和屬性。 |
2 | Drives |
Drives 是一個集合。 它提供了連接到系統的驅動器的物理或邏輯列表。 |
3 | File |
File 是一個對象。 它包含允許開發人員創建,刪除或移動檔的方法和屬性。 |
4 | Files |
Files 是一個集合。 它提供了一個檔夾中包含的所有檔的列表。 |
5 | Folder |
Folder 是一個對象。 它提供了允許開發人員創建,刪除或移動檔夾的方法和屬性。 |
6 | Folders |
Folders 是一個集合。 它提供了一個檔夾內所有檔夾的列表。 |
7 | TextStream |
TextStream 是一個對象。 它使開發人員能夠讀寫文本檔。 |
Drive
Drive
是一個對象,它提供對特定磁片驅動器或網路共用的屬性的訪問。 Drive
對象支持以下屬性 -
AvailableSpace
DriveLetter
DriveType
FileSystem
FreeSpace
IsReady
Path
RootFolder
SerialNumber
ShareName
TotalSize
VolumeName
示例
第1步 - 在使用FSO
進行腳本編寫之前,應該啟用Microsoft腳本運行時。請導航到工具->引用,如以下螢幕截圖所示。
第2步 - 添加“Microsoft腳本運行時間”,然後單擊確定。
第3步 - 添加想要寫入文本檔中的數據,這裏添加一個命令按鈕。
第4步 - 現在運行腳本。
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("F:\worksp\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
執行腳本時,請確保將游標放在工作表的第一個單元格中。 Support.log
檔的創建方式如下面“F:\worksp\vba”的目錄,如下的截圖所示。
該檔的內容,如以下螢幕截圖中所示 -
The Value at location (1,1)姓名
The Value at location (1,2)性別
The Value at location (1,3)城市
The Value at location (2,1)張三
The Value at location (2,2)男
The Value at location (2,3)北京
The Value at location (3,1)李四
The Value at location (3,2)男
The Value at location (3,3)北京
The Value at location (4,1)王五
The Value at location (4,2)男
The Value at location (4,3)上海
The Value at location (5,1)李小麗
The Value at location (5,2)女
The Value at location (5,3)深圳
The Value at location (6,1)Linsa
The Value at location (6,2)女
The Value at location (6,3)深圳
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
執行該腳本時,將在“F:\worksp\vba”位置創建“write.txt”檔,如以下螢幕截圖所示。
該檔的內容顯示如以下螢幕截圖 -
上一篇:
VBA Excel對象
下一篇:
VBA編程圖表