Bài này cung cấp cho bạn 2 phương thức để đọc nội dung file text trong VBA (plain text). Hãy xem các ví dụ sau đây:
Ví dụ 1: đọc toàn bộ nội dung file text trong vba bằng việc sử dụng đối tượng "ADODB.stream".
Public Const UTF_8_ENCODING = "UTF-8"
'-------------------------------------------
' read file example 1
'-------------------------------------------
Sub readFileExample1()
Dim fileName As String
Dim content As String
fileName = Application.ActiveWorkbook.path & "\" & "data.txt"
' call readFile() method
content = readFile(fileName, UTF_8_ENCODING)
' set content to cell "A1"
Cells(1, "A").Value = content
End Sub
'-------------------------------------------
' read file method
'-------------------------------------------
Function readFile(fileName As String, charSet As String) As String
Dim objStream As Object
Set objStream = CreateObject("ADODB.Stream")
objStream.charSet = charSet
objStream.Open
objStream.LoadFromFile (fileName)
readFile = objStream.ReadText()
Set objStream = Nothing
End Function
Ví dụ 2: đọc từng dòng một bằng việc sử dụng câu lệnh Open fileName và Close.
'-------------------------------------------
' read file example 2
'-------------------------------------------
Sub readFileExample2()
Dim fileName As String
Dim content As String
Dim textRow As String
fileName = Application.ActiveWorkbook.path & "\" & "data.txt"
' open file
Open fileName For Input As #1
' read line by line
Do While Not EOF(1)
Line Input #1, textRow
content = content & textRow & vbCrLf
Loop
' close file
Close #1
' set content to cell "A1"
Cells(1, "A").Value = content
End Sub
Ví dụ 3: đọc toàn bộ nội dung file text trong vba bằng việc sử dụng đối tượng Open fileName và Close.
'-------------------------------------------
' read file example 3
'-------------------------------------------
Sub readFileExample3()
Dim fileName As String
Dim content As String
Dim textRow As String
fileName = Application.ActiveWorkbook.path & "\" & "data.txt"
' open file
Open fileName For Input As #1
' read whole content
content = Input$(LOF(1), 1)
' close file
Close #1
' set content to cell "A1"
Cells(1, "A").Value = content
End Sub