brilliant
brilliant

Reputation: 2853

Creating a table in "MSWord" document out of a text in a .txt file

In the following file "E:\my_folder\my_future_table.txt" I have this text:

#   animal  country
1   rabbit  Germany
2   wolf    France
3   koala   USA

(please note that all the words in each line of that text are separated by tabs)

What VBS script do I need to use in order to create a "Word" file (.doc) with a table created on the basis of that text? (In this example, the table should have 3 columns and 4 rows)

Upvotes: 2

Views: 5145

Answers (1)

brettdj
brettdj

Reputation: 55672

Something like this with a healthy degree of credit to the Scripting Guy

  1. The vbs reads the test file (pls change your path), and then splits it by line break into an array ArrVar
  2. Each line in this array is split further by VbTab into a second array, ArrVar2
  3. The vbs creates a word table equal in size to the length of ArrVar and width of ArrVar2
  4. Each item is written to the table cell by cell, row by row

output

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add()

Set objRange = objDoc.Range()
strFilePath = "c:\temp\my_future_table.txt"

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTF = objFSO.opentextfile(strFilePath)
strAll = objTF.readall
arrVar = Split(strAll, vbNewLine)
numcols = UBound(Split(arrVar(0), vbTab)) + 1

objDoc.Tables.Add objRange, UBound(arrVar) - LBound(arrVar) + 1, numcols
Set objTable = objDoc.Tables(1)

For lngrow = LBound(arrVar) To UBound(arrVar)
    arrVar2 = Split(arrVar(lngrow), vbTab)
    For lngcol = LBound(arrVar2) To UBound(arrVar2)
     objTable.Cell(lngrow + 1, lngcol + 1).Range.Text = arrVar2(lngcol)
    Next
Next

objTF.Close
set objFSO = Nothing

objTable.AutoFormat (9)
objWord.Visible = True

Upvotes: 3

Related Questions