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
1

2 Answers 2

1

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

Set objTXT = objFSO.OpenTextFile("C:\...", ForReading)
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

That's an alternative but doesn't really answer the question asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.