Unable to use range.insertField for Online Word Addin

Chris Gay 0 Reputation points
2024-03-22T18:17:48.2066667+00:00

I am working on a Word Addin. We are trying to add in MergeFields into a Word document. The code below is working for the Desktop application, and adding a MergeField called 'StartDate' as expected. The same code is not working for the Online application. The range.insertField(...) is failing with an InvalidArgument.

            OfficeExtension.config.extendedErrorLogging = true
            Word.run(async (context) => {
                var body = context.document.getSelection()
                var range = body.getRange().load()
                const fieldName = 'StartDate'
                range.insertField(
                    Word.InsertLocation.before,
                    Word.FieldType.mergeField,
                    fieldName,
                    true
                )
                await context.sync()
            }).catch(function (error) {
                console.log('Trace Message:' + error.traceMessage)
                if (error instanceof OfficeExtension.Error) {
                    console.log('Trace Message:' + error.traceMessages)
                }
            })

The error is telling me the problem is at var insertField = range.insertField("Before", "MergeField", "StartDate", true); .

Any ideas as to why the Online Word is throwing this error?

Word
Word
A family of Microsoft word processing software products for creating web, email, and print documents.
686 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,563 questions
0 comments No comments
{count} votes