Search code examples
vbafilesystemobject

How to use the FileSystemObject in VBA


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

Solution

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

    Set objTXT = objFSO.OpenTextFile("C:\...", ForReading)