使用VBA宏将作者和注释从Word提取到Excel

时间:2018-04-12 17:55:54

标签: excel vba ms-word word-vba

我有以下代码从Word文档中提取文本字符串并将其导出到Excel电子表格中。 A列读取注释,B列读取它引用的原始文本。我还想提取在电子表格中发表评论的作者,但不知道该怎么做。感谢。

    Option Explicit




   Public Sub FindWordComments()
'Requires reference to Microsoft Word v14.0 Object Library

Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbooks.Open("C:\Users\cetraig\Documents\Projects\_HRBT\Book1.xlsx")

Dim myWord              As Word.Application
Dim myDoc               As Word.Document
Dim thisComment         As Word.Comment

Dim fDialog             As Office.FileDialog
Dim varFile             As Variant

Dim destSheet           As Worksheet
Dim rowToUse            As Integer
Dim colToUse            As Long

Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
Set destSheet = wb.Sheets("Sheet1")
colToUse = 1

With fDialog
    .AllowMultiSelect = True
    .Title = "Import Files"
    .Filters.Clear
    .Filters.Add "Word Documents", "*.docx"
    .Filters.Add "Word Macro Documents", "*.docm"
    .Filters.Add "All Files", "*.*"
End With

If fDialog.Show Then

    For Each varFile In fDialog.SelectedItems

        rowToUse = 2

        Set myWord = New Word.Application
        Set myDoc = myWord.Documents.Open(varFile)

        For Each thisComment In myDoc.Comments

            With thisComment
                destSheet.Cells(rowToUse, colToUse).Value = .Range.Text
                destSheet.Cells(rowToUse, colToUse + 1).Value = .Scope.Text
                destSheet.Columns(2).AutoFit
            End With

            rowToUse = rowToUse + 1

        Next thisComment

        destSheet.Cells(1, colToUse).Value = Left(myDoc.Name, 4)
        'Put name of interview object in cell A1

        destSheet.Cells(1, colToUse + 1).Value = ActiveDocument.Words.Count
        'Put the number of words in cell B1

        Set myDoc = Nothing
        myWord.Quit

        colToUse = colToUse + 2

    Next varFile

    End If

    End Sub

1 个答案:

答案 0 :(得分:0)

添加一行:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var myList = new List<SomeObj>() { new SomeObj(1, 10), new SomeObj(1, 20) };

        var sum = myList
             // filter for values of foo that equal 1
            .Where(c => c.foo == 1)
             // accumulate those values 
            .Aggregate(0m, (decimal acc, SomeObj next) => acc += next.prop);

        Console.WriteLine(sum);
    }
}

public class SomeObj
{
    public int foo { get; set; } = 1;
    public int prop { get; set; } = 10;

    public SomeObj(int foo, int prop)
    {
        this.foo = foo;
        this.prop = prop;
    }

}

应该做的伎俩

(假设您希望在下一栏中完成)