使用 R 在 Microsoft Word 中自动检索文件名 Table

Using R to Automate Filename Retrieval in a Microsoft Word Table

我在 Microsoft Word 文档中有一个很大的 table。

大多数行(但不是全部)都附加了一个 Microsoft Word 文件。

我的工作是进入每一行并手动输入提供附件的文件名。

有什么方法可以使用 R 包自动执行此任务吗?例如,对于有文件附件的每一行,自动提取文件名并将其直接记录在其左侧的字段中?

这就是 table 的样子。这些文件位于最右侧的列中。左边的栏是我要输入文件名的地方。

我已经尝试使用 docxtractr package 导入 docx 文件,但它没有正确读取文件名。相反,它将它们替换为 \s.

ievs_raw <- read_docx("ievs-raw.docx")

tbls <- docx_extract_all_tbls(real_world)

view(as.data.frame.list(tbls))

使用 \s 生成以下输出,其中应该有 CAP_ATT_H.11.114.docx 等文件名:

我无法使用 R 包来解决这个问题,但是 Microsoft Community Forum 的好心人提供了一个超级有用的 Visual Basic 宏来帮助解决这个问题。这有什么好处是它可以适应特定行中有超过 1 个附件的情况。

Sub ObjectNames()
    Dim ILS As InlineShape
    Dim nObj As Long
    Dim strName As String
    Dim col As Long
    Dim row As Long
    
    With ActiveDocument.Tables(1)
        col = .Columns.Count
        For row = 1 To .Rows.Count
            strName = ""
            
            # loop through all shapes in this row's last cell
            # (if there are none, the loop does nothing)
            For nObj = 1 To .Cell(row, col).Range.InlineShapes.Count
                Set ILS = .Cell(row, col).Range.InlineShapes(nObj)
                If Not ILS.OLEFormat Is Nothing Then
                    # build up a string with as many names as
                    # there are embedded objects, separated by
                    # paragraph marks (vbCr)
                    If nObj > 1 Then strName = strName & vbCr
                    strName = strName & ILS.OLEFormat.IconLabel
                End If
            Next nObj
            
            If Len(strName) > 0 Then
                .Cell(row, col - 1).Range.Text = strName
            End If
        Next row
    End With
End Sub