如何使用 Excel 宏将一段文本从 Word 复制到 Excel?

Rei*_* SE 5 excel vba ms-word excel-2007

对于多个文档,我需要使用 Excel 宏将特定文本项(一个或几个单词)从 Word (2007) 复制到 Excel (2007)。

到目前为止,我有 Excel 宏一次打开每个 Word 文档,并找到与我需要的文本相邻的文本。

我现在需要:

  1. 移至 Word 表格中的相邻单元格。我在想wdApp.Selection.MoveLeft Unit:=wdCell(或MoveRight)wdApp 在哪里Word.Application
  2. 复制单元格的内容。我在想像where is 之wdApp.Selection.Copy类的东西wdDoc.Word.Range,但我无法选择整个单元格内容。wdDocWord.Document
  3. 将其粘贴到 Excel 中的变量中。这里我不知道如何将剪贴板复制到 Excel 变量。

Tim*_*ams 5

更新以显示搜索文本,然后选择与其位置相关的内容:

Sub FindAndCopyNext()

    Dim TextToFind As String, TheContent As String
    Dim rng As Word.Range

    TextToFind = "wibble" 'the text you're looking for to
                          ' locate the other content

    Set rng = wdApp.ActiveDocument.Content
    rng.Find.Execute FindText:=TextToFind, Forward:=True

    If rng.Find.Found Then
        If rng.Information(wdWithInTable) Then
          TheContent = rng.Cells(1).Next.Range.Text      'move right on row
          'TheContent = rng.Cells(1).Previous.Range.Text 'move left on row
          MsgBox "Found content '" & TheContent & "'"
        End If
    Else
        MsgBox "Text '" & TextToFind & "' was not found!"
    End If

End Sub
Run Code Online (Sandbox Code Playgroud)

然后将变量 TheContent 分配给您所需的 Excel 范围。