I would like to refresh Excel tables in a Word template report programmatically using VBA. The tables are written to several sheets in a template Excel file from Matlab. The file structure will look like this:
The code would have to check the folder structure to see if it is pulling the Excel file out of the newest folder. If it was, it would just refresh all of the cells. If not, it would have to delete all of the tables and insert new ones from the same sheets as the previous ones were pulled. I am unsure of the code between the asterisks below. Any help would be much appreciated.
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
EDIT - The copy and pasting is done as shown below:
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…