Reputation: 23
So I'm quite new to VB and I'm just trying to create something that will open up a .txt file then read the first line and output it. I've put my code below but when I run it I get the error
Object variable or with block variable not set
because of the line
objTXT=objFSO.OpenTextFile("C:\...",ForReading)
Any help, I feel like I'm missing something quite basic.
Private Sub Text_Reader()
Dim objFSO As FileSystemObject
Dim objTXT As TextStream
Dim str$
Set objFSO = New FileSystemObject
objTXT = objFSO.OpenTextFile("C:\...", ForReading)
str = objTXT.ReadLine
MsgBox (str)
End Sub
Upvotes: 2
Views: 447
Reputation: 2526
The problem is not use Set
for opening. Try as follow:
Set objTXT = objFSO.OpenTextFile("C:\...", ForReading)
Upvotes: 1
Reputation: 3940
You don't need FileSystemObject
to read textfile.
You can do it like that (without any external libraries):
Public Sub readTextFile(filepath As String)
Dim intFile As Integer
Dim text As String
'------------------------------------------------------------------------------------------------------
intFile = VBA.FreeFile()
Open filepath For Input As #intFile
Line Input #intFile, text
Close intFile
Call MsgBox(text)
End Sub
Upvotes: 1