Word

Read Full Content Of Text File (Fast)

Ease of Use

Intermediate

Version tested with

2000, 2002 

Submitted by:

MOS MASTER

Description:

A fast way to read the entire contents of a txt file. This function will return it as a string. 

Discussion:

You need a way to display the content of a txt file in a userform or Message box. Both are in the attachment as examples to show how to call the function. 

Code:

instructions for use

			

Option Explicit ' \\ Function to return the full content of a text file as a string Public Function LoadTextFile(sFile As String) As String Dim iFile As Integer On Local Error Resume Next ' \\ Use FreeFile to supply a file number that is not already in use iFile = FreeFile ' \\ ' Open file for input. Open sFile For Input As #iFile ' \\ Return (Read) the whole content of the file to the function LoadTextFile = Input$(LOF(iFile), iFile) Close #iFile End Function ' \\ Test function to demonstrate LoadTextfile function Sub Test() Dim sPath As String ' \\ Path to text file sPath = ThisDocument.Path & "\dummy.txt" ' \\ Call the function passing the path to the txt file in a msgbox MsgBox LoadTextFile(sPath) End Sub

How to use:

  1. Open your document.
  2. Press Alt + F11 to open VBE.
  3. Insert-Module. (Insert -> module)
  4. Paste the code in the right (code) pane. (Ctrl + V)
  5. Close VBE (Alt + Q or press the X in the top right hand corner).
  6. Save the file.
 

Test the code:

  1. On open a userform will pop-up with the contents of the text file (example)
  2. To call the manual sub:
  3. press Alt + F8 to open the macro dialog box.
  4. Select Test
  5. Click Run.
 

Sample File:

Input Txt file.zip 11.14KB 

Approved by mdmackillop


This entry has been viewed 193 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express