Связанная таблица в MS Word
Я хотел бы обновить таблицы Excel в отчете шаблонов Word программно, используя VBA. Таблицы записаны на несколько листов в шаблонном файле Excel от Matlab. Структура файла будет выглядеть так:
Код должен проверить структуру папок, чтобы увидеть, вытягивает ли он файл Excel из самой новой папки. Если бы это было так, это просто обновило бы все клетки. Если нет, то придется удалить все таблицы и вставить новые из тех же листов, что и предыдущие. Я не уверен в коде между звездочками ниже. Любая помощь приветствуется.
Sub LinkToCurrentTableFolder()
'Get current folder by date
Dim clientTablesPath As Variant
filePath = ActiveDocument.Path & "\ClientTables\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(filePath)
Dim currentFolder As Variant: currentFolder = ""
For Each sf In fld.SUBFOLDERS
'Look at name and get current date
If currentFolder = "" Then
currentFolder = sf.Path
ElseIf sf.Path > currentFolder Then
currentFolder = sf.Path
End If
Next
'***
'Debug: display current Excel folder path
'MsgBox (currentFolder)
If currentPath = currentFolder Then
'Loop through all tables in document and refresh
'If path is not current delete current table
Dim tbTemp As Table
Dim cellTemp As Cell
For Each tbTemp In ActiveDocument.Tables
For Each cellTemp In tbTemp.Range.Cells
cellTemp.Range.Fields.Update
Next
Next
Else
'Locate same file name in new folder
shpName = .LinkFormat.SourceName
NewPath = currentFolder & "\" & shpName
'Delete existing table (???) Not sure
.Delete
'Create new table (???) Not sure - must be from same location and same size as previous one
Selection.Table.AddOLEObject ClassType:=cType, FileName:=NewPath, LinkToFile:=True, DisplayAsIcon:=False
End If
'***
End Sub
РЕДАКТИРОВАТЬ - Копирование и вставка выполняется, как показано ниже: