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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7338385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 13:58:42  来源:igfitidea点击:

How can I copy one section of text from Word to Excel using an Excel macro?

excelvbams-wordexcel-2007

提问by Reinstate Monica - Goodbye SE

I need to copy a specific item of text (one or a few words) from Word (2007) to Excel (2007) using an Excel macro, for multiple documents.

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

So far I have the Excel macro opening each Word document one at a time and locating the text adjacent to what I need.

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

I now need to:

我现在需要:

  1. Move to an adjacent cell in a Word table. I'm thinking wdApp.Selection.MoveLeft Unit:=wdCell(or MoveRight) where wdApp is Word.Application
  2. Copy the contents of the cell. I'm thinking wdApp.Selection.Copyand something like wdDoc.Word.Rangewhere wdDocis Word.Documentbut I can't select the whole cells contents.
  3. Paste it into a variable in Excel. Here I don't know how to copy the clipboard to an Excel variable.
  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 变量。

采纳答案by Tim Williams

Updated to show searching for text and then selecting content relative to its location:

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

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

Then assign the variable TheContent to your required Excel range.

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