简体   繁体   English

将数据从 MS Word 移动到 Excel

[英]Move data from MS Word to Excel

I have a Microsoft Word document with 400 multiple choice test questions.我有一个包含 400 道选择题的 Microsoft Word 文档。 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.我需要将所有这些文本放入 Microsoft Excel 图表中,我认为如果我能够拥有一个允许我选择所有以a.开头的文本的宏会容易得多a. and ends the section at the first paragraph object after a.并在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 ctrl and highlight all the text that begins with a.如果我要在 Microsoft Word 中手动执行此操作,我会按住ctrl并突出显示所有以a.开头的文本a. and ends at the first paragraph object.并在第一个段落对象处结束。

 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

ThisDocument typically refers to the template document containing the executing code. ThisDocument通常是指包含执行代码的模板文档。 Use ActiveDocument instead.请改用ActiveDocument

Also as @assylias said in his comment, Debug.Print is only for code debugging purposes.同样正如@assylias 在他的评论中所说, Debug.Print仅用于代码调试目的。 Replace that entire line with .Range.Select ..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 KB288424 for more).编辑:在查看并测试 lorem ipsum 文本后,我意识到 Word VBA 不允许您选择多个不连续的段(有关更多信息,请参阅 MS 支持文章KB288424 )。 I suppose the easiest way then is to simply export to excel where the debug.print is and I have edited my code accordingly.我想最简单的方法是简单地导出到 debug.print 所在的 excel,我已经相应地编辑了我的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM