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
How can I copy one section of text from Word to Excel using an Excel macro?
提问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:
我现在需要:
- Move to an adjacent cell in a Word table. I'm thinking
wdApp.Selection.MoveLeft Unit:=wdCell
(orMoveRight
) where wdApp isWord.Application
- Copy the contents of the cell. I'm thinking
wdApp.Selection.Copy
and something likewdDoc.Word.Range
wherewdDoc
isWord.Document
but I can't select the whole cells contents. - Paste it into a variable in Excel. Here I don't know how to copy the clipboard to an Excel variable.
- 移至 Word 表格中的相邻单元格。我在想
wdApp.Selection.MoveLeft Unit:=wdCell
(或MoveRight
)wdApp 在哪里Word.Application
- 复制单元格的内容。我在想像where is 之
wdApp.Selection.Copy
类的东西wdDoc.Word.Range
,但我无法选择整个单元格内容。wdDoc
Word.Document
- 将其粘贴到 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 范围。