将注释从Word导出到Excel

时间:2019-06-05 19:04:55

标签: vba ms-word

当我尝试在Word中运行以下代码以提取注释时,出现错误。黄色突出显示在Public Sub PrintFirstColumnOnActiveSheetToSheetName()上方,然后显示我有一个编译错误:未定义变量,并在代码底部突出显示了Activesheet.range(“ A1”)中的“ Activesheet”

Option Explicit

Public Sub FindWordComments()


Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbooks.Open("C:\Desktop\Book11")

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("Book11")
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


Public Sub PrintFirstColumnOnActiveSheetToSheetName()


ActiveSheet.Name = ActiveSheet.Range("A1")


End Sub

2 个答案:

答案 0 :(得分:1)

由于未定义Activesheet,因此也许应该使用destSheet而不是Activesheet。否则,您应该为Activesheet加上objExcelApp前缀,这样:

objExcelApp.Activesheet

答案 1 :(得分:0)

由于您是在Word中运行此程序,因此VBA仅“知道”属于Word 对象模型的内容,除非代码明确指出了其他对象模型是源。 Word对“ Sheets”一无所知-只有Excel知道ActiveSheet是什么。

即使您显示给我们的代码没有调用过程PrintFirstColumnOnActiveSheetToSheetName()(使用ActiveSheet的过程),VBA在编译代码时也会看到它。因此,您需要将对Excel应用程序的引用传递给此过程并使用它。例如:

Public Sub PrintFirstColumnOnActiveSheetToSheetName(objExcel as Object)
  objExcel.ActiveSheet.Name = objExcel.ActiveSheet.Range("A1")
End Sub

要在代码的其他位置调用它,它看起来类似于以下行。请注意,在不同的过程中,同一对象的变量名称不必相同-可以相同,但是没有必要。 VBA“记住” Excel应用程序先前启动的是传递给另一个过程的信息。

PrintFirstColumnOnActiveSheetToSheetName objExcelApp
相关问题