Bài này cung cấp bạn 2 phương thức để ghi file text trong VBA (plain text). Hãy xem các ví dụ sau đây:
Ví dụ 1: Ghi file text trong VBA bằng việc sử dụng đối tượng "ADODB.stream".
Public Const UTF_8_ENCODING = "UTF-8" '------------------------------------------- ' write file example 1 '------------------------------------------- Sub writeFileExample1() Dim fileName As String Dim content As String content = "Hello, Admin!" & vbCrLf & "Write data to text file example." fileName = Application.ActiveWorkbook.path & "\" & "ouput.txt" Call writeFile(fileName, UTF_8_ENCODING, content) End Sub '------------------------------------------- ' write file method '------------------------------------------- Sub writeFile(fileName As String, charSet As String, content As String) Dim objStream As Object Set objStream = CreateObject("ADODB.stream") objStream.Type = adTypeText objStream.charSet = charSet objStream.Open objStream.WriteText content objStream.SaveToFile fileName, adSaveCreateOverWrite Set objStream = Nothing End Sub
Ví dụ 2: Ghi file text trong VBA bằng việc sử dụng Open fileName For Output As #1.
'------------------------------------------- ' write file example 2 '------------------------------------------- Sub writeFileExample2() Dim fileName As String Dim content As String content = "Hello, Admin!" & vbCrLf & "Write data to text file example." fileName = Application.ActiveWorkbook.Path & "\" & "ouput.txt" ' open file as output Open fileName For Output As #1 ' write content to file Write #1, content ' close file Close #1 End Sub