简体   繁体   中英

Creating a word document from excel: adding headings

I have some VBA code in an Excel workbook (.xlsm) that I use to create an Appendix as a word document from the worksheets in that workbook. The existing code works. I modified code from this site: https://hackernoon.com/how-to-create-word-documents-within-excel-vba-d13333jl

The problem is this. I think I'm not actually creating real headings. I am bolding some parts and changing the font size; but it's not quite what I want. I want to make them real headings. What do I mean by that? If I open a word document manually I can select text, then go to the main ribbon and click on "Heading 1" and it will change the font style, etc. If I create a file manually in this way, then I can manually create a table of contents (TOC) pretty easily. Eventually I would like to generate the TOC automatically as well, but for now, if I can just create these things as headers, it would solve problem.

So I want to go into this code and where it says.BoldRun, I would like to say something like ".Heading 1" or ".Heading 2." BUT... Word doesn't recognize those objects. There is a.HeaderFooter object. There is a.SoryByHeaders method... but no obvious way to create text as header.

It occurs to me that I may be making a false assumption. I've been thinking of a header as an object in itself, rather than a collection of formatting. that is, I thought when - in a Word - document I go to the home ribbon and select some text and click on say "Heading 1" and then click on some other text and click "Heading 2" that it did more just format the text - that it somehow marked it or tagged it as "this is a heading of type 1", etc? Is that false? That is, if I make something a Heading 1, does it really just add formatting to it?

How to I make the bolded text in the sample code below into actual "Headings" at level 1, 2, 3?

Sub create_word_document()

    Dim lead As String
    
    Dim app As word.Application
    Set app = New word.Application
    app.Visible = True
    app.Activate
    
    start_index = 1
    With app
        Category = 0
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
            .Style = wdStyleHeading1
            .TypeText Trim(Str(start_index)) & " Appendix Name"
            .TypeParagraph
            For i = 1 To 20
                .TypeText "Ipsum Lorem"
            Next i
            .TypeParagraph
            
            For Each sht In ThisWorkbook.Sheets
                If sht.Name <> "Completion Index" And sht.Name <> "For Coding" Then
                    Category = Category + 1
                    
                    lead = Trim(Str(start_index)) & "." & Trim(Str(Category))
                    .Style = wdStyleHeading2
                    .TypeText lead & " " & sht.Name

                    .TypeParagraph
                    '.TypeText "Definition words for category"
                    .TypeParagraph
                    
                    For r = 2 To 50
                        If sht.Cells(r, 1).Value <> "" Then
                            inspection_name = sht.Cells(r, 1)
                            inspection_definition = sht.Cells(r, 4)
                            inspection_short_name = sht.Cells(r, 2)
                            lead = Trim(Str(start_index)) & "." & Trim(Str(Category)) & "." & Trim(Str(r - 1))
                            .Style = wdStyleHeading3

                            .TypeText lead & " " & inspection_name & " (" & inspection_short_name & ")"
                            
                            .TypeParagraph
                            .TypeText inspection_definition
                            .TypeParagraph
                            
                        End If
                    Next r
                    .TypeParagraph
                End If
            Next sht
            
        End With
        '.ActiveDocument.SaveAs2 "C:\Projects\4803_GAIT\Inspections Description Revisions\inspections.docx"
        '.ActiveDocument.Close
        '.Quit
    End With

End Sub

Migrating solution from the question to an answer:

Note: This question was answered in the comments by Timothy Rylatt. The code at bottom is what I want. So that's the answer. Of interest to me is how I got to the answer.

The big hint was following up on Timothy's comment below: Use Record Macro to figure out the call. I needed to add the Developer Ribbon to do that. (File --> options --> Customize Ribbon... then scroll down and select Developer)... That adds the Developer Tab.

Go to new developer tab, click record macro, go back to main text, select a word. Go to Home tab, select "Heading 1" for example, then go back to developer tab and click "stop recording." select "macros" and whatever name you gave the macros and edit.

Slightly tricky part. It records:

 Selection.Style = ActiveDocument.Styles("Heading 1")

That won't work for some reason, so I googled "excel activedocument.styles" That took me to this page: https://docs.microsoft.com/en-us/office/vba/api/word.document.styles

The next hint was I saw the term wdStyleHeading1. The exact code there also does not work. I just experimented around until I got something that works. On the other hand, Timothy had typed the answer.

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