VBA code to read word document footer

2019-09-02 07:26发布

I have a folder of completed word document forms and I have an excel file that reads all the answers on the forms into different worksheets in spreadsheet. The worksheet that the data is exported to depends on the filename of the word document.

This currently works fine.

However, I now need it to be able to take into account the version number of the form which is stored in the footer of the word document but I don't know how to reference it.

I'm quite a noob when it comes to VBA so havent tried much.

The VBA that I have tried can be found below but unsurprisingly doesnt work.

Sub ReadWordDoc(filenme As String)

Dim Val As String
Dim WrdDoc As Document
Dim FormFieldCounter As Integer

Dim version As String

Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open filenme
wordapp.ScreenUpdating = False

Set WrdDoc = wordapp.Documents(filenme)
wordapp.Visible = True

version = WrdDoc.Sections(1).Footers(wdHeaderFooterFirstPage).Range.Text

FormFieldCounter = 1

If InStr(version, "5.00") Then

    RowCounter = RowCounter + 1

    Sheets("Version 5").Cells(RowCounter, FormFieldCounter) = filenme

    Do While FormFieldCounter <= 125
    WrdDoc.FormFields(FormFieldCounter).Select
    Val = WrdDoc.FormFields(FormFieldCounter).result
    Sheets("Version 5").Cells(RowCounter, FormFieldCounter + 1) = Val

    FormFieldCounter = FormFieldCounter + 1

    Loop

    wordapp.Documents(filenme).Close SaveChanges:=wdDoNotSaveChanges
    wordapp.Quit

Else

    'Do something else

End If


End Sub

1条回答
贪生不怕死
2楼-- · 2019-09-02 07:56

After having a bit of a play and a Google, I found this page which helped me fix my issue https://msdn.microsoft.com/en-us/library/office/aa221970(v=office.11).aspx

I changed my code as below:

version = WrdDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text

Although I'm not sure why the previous version didnt work as there is a footer on the first page.

查看更多
登录 后发表回答