简体   繁体   中英

How to Format Text Style to "Heading 1" while importing all Txt files into Word document

I used this method to import all files into Word document.

https://stackoverflow.com/a/30494740/908080

I added to include File Name before the content text like this

With wdDoc.Range
     .InsertAfter FileCnt & ". "
     .InsertAfter myFile & vbCr
     .InsertParagraphAfter
     .InsertAfter txtFiles.Range.Text & vbCr
End With

It works fine. Is it possible to Set the Format for FileName Text to be "Heading 1" and rest content as Normal Text. Once done, I can create a TOC and go to the required file quickly.

So it need to look like

1. File1.Txt

This is File1 Text

2. File2.Txt

This is File2 Text

It's possible, but doing it (easily) requires a slightly different approach for handling the target Range . Something more like this (untested):

Dim rng as Word.Range
Set rng = wdDoc.Content 'a property that returns a Range; Doc.Range is a method
rng.Collapse wdCollapseEnd
With rng
     .Text = FileCnt & ". " &  myFile & vbCr
     .Style = wdStyleHeading1
     .Collapse wdCollapseEnd
     .Text = vbCr & txtFiles.Range.Text & vbCr
     .Style = wdStyleNormal
End With

Think of working with a dedicated Range object like working with a Selection - "collapsing" is like pressing an arrow key. So enter content, format, then go to the end (or the start). Then repeat for the next content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM