Here is a quick little VB/VBA function to turn text files (or html files or xml files) into string variables.
Text File to String Variable Function (xml file to string variable, html file to string variable)
There are numerous Internet Programming situations where large pieces of text need to be populated with variable values. On other occasions the task could be parsing html files to retrieve SEO information. Yet another common situation is working with XML as a string inside VB. The Microsoft XML objects consume a lot of memory. Sometimes it is more efficient to work with XML as a string instead of consuming the overhead necessary to create XMLHTTP or MSXML objects.
You can also use a xml file as a template for SOAP calls. Simply retrieve the xml as a string, populate some predefined placeholder text and you are ready to call inline webservices. As you’ll see, turning text into a string is easy – it doesn’t matter whether it is xml to string or html to string either.
The TextToString Function
The function below is short and relatively straightforward – feel free to customize it to suit your individual needs. It contains some rudimentary error trapping, but it should be enough to catch common errors and display enough information for easy troubleshooting.
The function contains two variables: the strPath variable is the argument parameter that will contain the absolute path to the file. You may want to implement file extension validation if your project requires a little more ‘tightness’ in the code. strBuff acts as a temporary buffer to hold the results until they can be assigned back to the function’s result.
Public Function XMLToString(strPath As String) As String
Public Function HTMLToString(strPath As String) As String
Public Function TextToString(strPath As String) As String
Dim strBuff As String
On Error GoTo ErrTrap
Open strPath For Binary As #1
strBuff = Space(LOF(1))
Get #1, , strBuff
TextToString = strBuff
If Err Then Err.Raise Err.Number, , “Error from Functions.TextToString ” & Err.Description
In a later project, we’ll be combining this Text to String Function with the Loop Through Directory routine in order to build content for a WordPress blog. We’ll examine how to create upload files by manipulating data in Excel.
Wise Man Say, Don’t Run Your Head Against a Stone Wall
Popularity: 4% [?]