【问题标题】:Extract Data/controls from Word to Excel将数据/控件从 Word 提取到 Excel
【发布时间】:2019-06-19 20:12:38
【问题描述】:

目前我有一个 Word 文档,它是一份问卷。

格式(共 30 题):

姓名:

1. Question
YES checkbox
NO checkbox
Comments

2. Question
YES checkbox
NO checkbox
Comments

复选框和 cmets 是控件。

我要做的是将复选框和注释数据提取到excel中。例如,

1. Do you spend time under the sun?
YES checkbox is selected
Comments: I spend 2 days out of the week in the sun.

我希望它在 excel 中显示的是什么。

每次运行宏时,都应在现有记录(行)下方添加新信息。

我通常使用Word,将excel中的数据提取到word中,但我从未尝试过。

这是我目前想出的:

Sub Macro1()
    Application.ScreenUpdating = False
    Dim lRow As Long, i As Long, j As Long, iCtr As Long, cBox As CheckBox, StrFlNm As String
    With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
        SendKeys "%n *.doc ~"
        If .Show = True Then
            StrFlNm = .SelectedItems(1)
        Else
            Exit Sub
        End If
    End With
    Application.Volatile

    For Each cBox In ActiveSheet.CheckBoxes
        If cBox.Value = 1 Then
            iCtr = iCtr + 1
        End If
    Next cBox
    CheckedCount = iCtr
End Sub

它会选择文件,但没有任何反应。如果我能确定如何将其应用于一个复选框,我应该能够弄清楚如何完成其​​余的工作。我会随着我们继续更新代码,我已经更改了很多次。

激活 Microsoft Object 并运行新代码。选择文件后,系统会提示我此消息。

【问题讨论】:

    标签: excel vba ms-word


    【解决方案1】:

    你的代码的前半部分只是给你一个文件名。那时,Excel 对文档的内容一无所知。
    在这里,您需要打开文档,为此您需要引用 Word 的对象模型。 在工具 - 参考中,选择 Microsoft Word nn 对象库。
    现在,Excel 可以处理 Word 文档了。

    做这样的事情:

    Sub Macro1()
        Dim lRow As Long, i As Long, j As Long, iCtr As Long, cBox As ContentControl, StrFlNm As String
    
        With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
            SendKeys "%n *.doc ~"
            If .Show = True Then
                StrFlNm = .SelectedItems(1)
            Else
                Exit Sub
            End If
        End With
    
        Application.Volatile
    
        Dim Doc As Word.Document
        Set Doc = Word.Documents.Open(StrFlNm)
        Debug.Print Doc.Range.ContentControls.Count
    
        For Each cBox In Doc.Range.ContentControls
            If cBox.Checked Then
                iCtr = iCtr + 1
            End If
        Next cBox
        CheckedCount = iCtr
        Doc.Close
    End Sub
    

    【讨论】:

    • 取得进展。选择文件后,我会弹出错误消息,但错误消息为空白。我将发布错误消息。 @山姆
    • 暂时删除整个With块并硬编码StrFlNm。这将帮助您找出问题所在
    • 对于一些成熟的代码,请参阅:msofficeforums.com/word-vba/…
    • Sam,我在代码中看不到您实例化 Word 应用程序的任何地方。我希望这就是@LOZ 出错的原因。问题中的代码是在 Excel 中运行的,所以没有 Word 应用程序可以打开 Word 文档...
    • @CindyMeister - 我刚刚试过。它无需显式实例化即可工作。
    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多