I'm trying to set up a button in MS Word to update the linked Excel data source behind charts. I'll say upfront that I know this is easy with built-in functionality, but I'd like to use a button for those uncomfortable navigating the menus. Also, I've read and drawn from some great articles on this topic in general, but am getting an error not referenced in those pieces.
Testing has shown that Word a) identifies the Excel link as a field (vs a shape) and b) flags this field as type 87 (OCX). When I run the code below, it generates an "object variable or With block variable not set" error. However this appears to possibly be rooted in the field type based on this Microsoft article.
I'm struggling to find an alternative method and would appreciate help... this is my first foray into VBA for Word. Thanks!
Sub CommandButton1_Click()
Dim MyNewFile As Variant
Dim fDialog As FileDialog, result As Integer
Dim fieldCount As Integer
'Set up file dialog
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Select a file"
.Filters.Clear
.Filters.Add "Excel files", "*.xlsx,*.xlsb,*.xlsm,*.xls"
End With
'Show the dialog, store the file name
If fDialog.Show = -1 Then
MyNewFile = fDialog.SelectedItems(1)
End If
fieldCount = ActiveDocument.Fields.Count
For k = 1 To fieldCount
With ActiveDocument.Fields(k)
If .Type = 87 Then
With .LinkFormat
.SourceFullName = MyNewFile 'BLOWS UP HERE
.AutoUpdate = True
End With
End If
End With
Next k
End Sub