我想使用 VBA 以编程方式刷新 Word 模板报告中的 Excel 表格。这些表格被写入 Matlab 模板 Excel 文件中的几张纸上。文件结构将如下所示:
该代码必须检查文件夹结构以查看它是否将 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
编辑 - 复制和粘贴如下所示: