data to text vba code example

Example 1: excel vba write string to text file

'VBA function to write string to text file:

Function SaveStringAsTextFile$(s$, fName$)
    Const adSaveCreateOverWrite = 2
    With CreateObject("ADODB.Stream")
        .Charset = "utf-8"
        .Open
        .WriteText s
        .SaveToFile fName, adSaveCreateOverWrite
    End With
End Function

Example 2: excel vba open text file

'VBA function to open text file and retrieve the entire content
'as a string:

Function OpenTextFile$(f)
    With CreateObject("ADODB.Stream")
        .Charset = "utf-8"
        .Open
        .LoadFromFile f
        OpenTextFile = .ReadText
    End With
End Function

'--------------------------------------------------------------------

s = OpenTextFile("C:\123.json")
MsgBox Len(s)

Tags:

Vb Example