Search code examples
vbafso

Writeline in VBA breaks with too long text


I am automating a web page extraction and writting the contents to a text (HTML) file.

For that I set up a File System Object like this

Dim myHTMLfilepath As String
myHTMLfilepath = "C:\temp\MyFile.html"

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim myHTMLFile As Object
Set myHTMLFile = fso.createtextfile(myHTMLfilepath)

When I try to write the extracted content to the file sometimes I get an error 5 (invalid parameter). Here is th code:

myHTMLFile.writeline objIE.document.getElementsByClassName("cool-box")(0).innerHTML

It breaks when the length of the innerHTML is somewhere between 25800 and 28000 (I haven't yet figured the exact limit).

Does anyone know if the WriteLine limit can be increased or advise on a different way to do this?


Solution

  • Assuming the .innerHTML can successfully be read into a string (split up reading/writing to find out), you should be able to use an ADODB.Stream to write it to the file. WriteLine is intended to write a single line of text to a file, not a whole entire document.

    Dim contents As String
    contents = objIE.document.getElementsByClassName("cool-box")(0).innerHTML
    
    With CreateObject("ADODB.Stream")
        .Open
        .Type = 1
        .Write contents
        .SaveToFile myHTMLfilepath, 2
        .Close
    End With