vba 将数据从 MS Word 移动到 Excel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10900945/
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
Move data from MS Word to Excel
提问by user1437779
I have a Microsoft Word document with 400 multiple choice test questions. I need to put all this text into a Microsoft Excel chart and I thought it would be alot easier if I was able to have a macro that allowed me to select all text that began with a.
and ends the section at the first paragraph object after a.
.
我有一个包含 400 道选择题的 Microsoft Word 文档。我需要把所有的文字到Microsoft Excel图表,我认为这将是一个容易得多,如果我能有一个让我选择与开始的所有文字宏a.
结束后,在第一段对象的部分a.
。
I tried getting help and was told to use the below macro but the macro does not do anything. I just want the macro to select all the text only. If I were to do this in Microsoft Word manually, I would hold down ctrland highlight all the text that begins with a.
and ends at the first paragraph object.
我尝试寻求帮助并被告知使用下面的宏,但该宏没有做任何事情。我只希望宏只选择所有文本。如果我在 Microsoft Word 中手动执行此操作,我会按住ctrl并突出显示a.
以第一个段落对象开头和结尾的所有文本。
Sub Aselection()
'
' Aselection Macro
'
Dim pgh As Paragraph
For Each pgh In ThisDocument.Paragraphs
With pgh
If Left(.Range.Text, 2) = "a." And Left(Right(.Range.Text, 3), 2) = "a." Then
Debug.Print .Range.Text
End If
End With
Next
End Sub
回答by 147
ThisDocument
typically refers to the template document containing the executing code.
Use ActiveDocument
instead.
ThisDocument
通常是指包含执行代码的模板文档。使用ActiveDocument
来代替。
Also as @assylias said in his comment, Debug.Print
is only for code debugging purposes.
Replace that entire line with .Range.Select
.
同样正如@assylias 在他的评论中所说,Debug.Print
仅用于代码调试目的。用 替换整行.Range.Select
。
This should work:
这应该有效:
Sub Aselection()
Dim o As Object
Dim pgh As Paragraph
Set o = CreateObject("excel.application")
o.workbooks.Open ("E:\Aashay Data\Projects\Excel\Carton\Screen Printing.xlsx")
o.ActiveWorkbook.worksheets.Add.Name = "x"
o.ActiveWorkbook.worksheets("x").Activate
For Each pgh In ActiveDocument.Paragraphs
With o.ActiveWorkbook.worksheets("x")
Debug.Print pgh.Range.Text
If Left(pgh.Range.Text, 2) = "a." And Left(Right(pgh.Range.Text, 3), 2) = "a." Then
.Cells(i, 2).Value = pgh.Range.Text
i = i + 1
End If
End With
Next
o.Quit
End Sub
EDIT: After reviewing this and testing a lorem ipsum text, I realised that Word VBA does not allow you to select multiple discontinuous segments (See MS Support article KB288424for more).
I suppose the easiest way then is to simply export to excel where the debug.print is and I have edited my code accordingly.
编辑:在查看并测试 lorem ipsum 文本后,我意识到 Word VBA 不允许您选择多个不连续的段(有关更多信息,请参阅 MS 支持文章KB288424)。我想最简单的方法是简单地导出到 debug.print 所在的 excel,我已经相应地编辑了我的代码。