2

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
Tabitha
  • 23
  • 2
  • You're just missing a `Set` keyword in front of `objTXT = ...` [MSDN Reference to OpenTextFile](https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx) and a [bit more here on SO](http://stackoverflow.com/q/349613/2140173) –  Jul 22 '15 at 10:22

2 Answers2

1

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
mielk
  • 3,890
  • 12
  • 19
  • 3
    That's an alternative but doesn't really answer the question asked. –  Jul 22 '15 at 10:19
1

The problem is not use Set for opening. Try as follow:

Set objTXT = objFSO.OpenTextFile("C:\...", ForReading)
R.Katnaan
  • 2,486
  • 4
  • 24
  • 36