This VBA code will help you to import data from a text file and insert into the MS word document. This is useful when you have to create a report or formats in the in MS Word format, reading the data from a text file. The VBA code can be extended import extra data from the text file, and also you can add additional format as per your needs.
Please note that VBA macros can cause harm to your computer. First, open them in a disabled mode. To disable macros, to Developer tab, select macro security and then select Macro settings on the left side pane. In the right pane, select the second radio button, 'Disable all macros with notification'. The second option is better because it will notify you if there are any macros associated with your file. So you will not miss any document features which may be available after running a macro. But you can decide whether to allow the macros to run or not.
Please click on the below link to download the MS Word Template file. You can also download the text file used to import the data. I remind you that this is a sample file. You may have to modify the VBA code according to your requirement. You may have to rename the input file.
Please leave comment below if you have any concerns.
MS word template
The VBA Code
If (ActiveDocument.Name = "Template.docm") Then
On Error Resume Next
.Variables.Add Name:="1", Value:="1"
.Variables.Add Name:="2", Value:="2"
.Variables.Add Name:="3", Value:="3"
.Variables.Add Name:="4", Value:="4"
.Variables.Add Name:="5", Value:="5"
.Variables.Add Name:="6", Value:="6"
Dim ReadData As String
Dim myarray() As String
Open ActiveDocument.Path & "\text.txt" For Input As #1
Do Until EOF(1)
Line Input #1, ReadData
If Not Left(ReadData, 1) = "*" Then
myarray = Split(ReadData, ",")
i = 1
For Each f In myarray
.Variables(i).Value = f
i = i + 1
strFileName = "Agreement Between " & myarray(5) & " and " & myarray(0)
strPath = .Path
.SaveAs2 (strPath & "\" & strFileName)
Tuesday, August 22, 2017
There are situations where you may have to copy and paste some content from excel to word. And save the newly created document into disk. Th...
Normal phone Bluetooth headset can be easily connected to a laptop and it can be used as earphone or headphone while using skype, gtalk, wha...
There are plenty of online resources to convert Numeric currencies to Text- from $200 to Dollar Two Hundred. But this is applicable only ##...
MS Excel currency converter 3.0 has been updated with bug fixes. This is the new version of my amazing currency converter VBA utility for MS...