【问题标题】:Scraping Word with Excel VBA用 Excel VBA 刮字
【发布时间】:2016-01-27 13:04:16
【问题描述】:

我有一个充满报纸文章的 Word 文档。每篇报纸文章前面都有文章标题和字符串“Length:”,后面是文章的字数(即“Length: 1500 words”)。我只需要一个 Excel 宏来梳理 Word 文档并提取每篇文章的长度值 - 将这些值放在 Excel 列中。

通过我的谷歌搜索,我发现了这个:Extract Data from Word Document to an Excel SpreadSheet

几乎是我需要的,但它只返回搜索找到的第一篇文章长度值。如何修改代码以查找每篇文章的长度值,将这些值返回到 Excel 列然后终止?

【问题讨论】:

  • 所以您现在的问题是循环文件并写入 Excel 工作表?请尝试一些想法,并针对您遇到的代码问题提出具体问题。现在你的问题很笼统,主要是要求人们为你编写代码......

标签: vba excel ms-word


【解决方案1】:

您链接的代码不是特别健壮。我已经在 Excel (ExR(1, 1) = WDR ' place at Excel cursor) 中提取了对单元格的分配,并围绕它构建了更强大的 Word 代码。

代码使用 Word Range 对象而不是 Selection。这更有效,更可预测,屏幕不会跳来跳去。 Find 使用通配符搜索特定文本,加上“Length”和“words”之间的数字。由于成功的 Find 包括找到的 Range,因此只需将 Range 的 Text 分配给 Excel 中的单元格。

Find plus 赋值内置在一个 LOOP 中,只要 Find.Execute 成功,它就会运行。对于 Excel 中的单元格分配,COUNTER 在每个循环中递增,因此您无需对目标单元格索引进行硬编码。

Dim strFind As String
Dim rngFind As word.Range 'or As Object if you don't set a Reference to the Word object library
Dim bFound As Boolean
Dim iCellCounter As Long

strFind = "Length: [0-9]{1;} words"
bFound = False
iCellCounter = 1
Set rngFind = WApp.ActiveDocument.Content
With rngFind.Find
    .ClearAllFuzzyOptions
    .ClearFormatting
    .ClearHitHighlight
    .Format = False
    .MatchWildcards = True
    .Text = strFind
    .wrap = wdFindStop   '0 if you don't use a Reference to the Word object library
    Do
        bFound = .Execute
        If bFound Then
            ExR(1, iCellCounter) = rngFind.Text
            iCellCounter = iCellCounter + 1
        End If
    Loop While bFound
End With

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多