Search code examples
vbaimportms-wordfieldbookmarks

Filling Word Fields from a .DAT file with VBA


I'm working with a Java application that is going to write a .dat file that is supposed to be used as a template to fill a Word template that has fields and bookmarks in it. I've spent quite awhile searching for information on .dat files being used to template a Word field/bookmark and I've yet to come up with anything.

I have the VBA code written to go and get the file, but I have two large problems that I can't seem to locate the answer to. I'd appreciate if someone could answer the following:

  1. What should the .dat file code look like? (not the code to generate it, have that, but how should it be formatted to achieve the desired result)

  2. After I open the .dat file with VBA, do I need to do anything code-wise to have it replace the fields/bookmarks with its data?

Currently I do have the code to go out and get the .dat file and open it. I have code written to do inserts for bookmarks and fields, but seeing as how I wasn't sure if there was a specific structure to.dat files for vba to read, I didn't know if it was pertinent or not. Thank you to Jean-François Corbett and Roman for clarifying this.

Taking this into consideration, I've decided to use the following .dat file format.

File.dat
RequisitionHeader_requisitionNumber=11-2019
RequisitionHeader_poNumber=889-0936
RequisitionHeader_orderDate=11/12/1901

With that, using the VBA I have now that opens the file, do I need to write a text parser inside of VBA to find and replace values into the corresponding field/bookmarkName?


Solution

  • OK, now one can understand better. So you have already code to loop through bookmarks and fields and put values in it, and your problem is to know how you can read data from a file with VBA. Please keep in mind that VBA is nothing else then an Visual Basic 6.0 integrated in an Office application. So accessing files is restricted to the old Basic I/O procedures. You can find first information here. On the other hand, while working with VBA you can always use the Windows Scripting Host to read all lines of a text file into memory/into a variable, like this:

    Set fso=CreateObject("Scripting.FileSystemObject")
    If fso.FileExists(FileName) Then
       Set f=fso.OpenTextFile(FileName,1)
       Content=f.ReadAll
       f.close
       (rest ommitted)
    

    Afterwards you're free to parse your text as you like it, e.g. using the Split function to convert all lines first into an array, and then to get the values from each line.

    There's also the old approach to use the functions related to INI files; you may find this in some old handbooks. Here you should keep in mind that the Windows API function for INI files don't read more than 256 characters after the = sign.