循环访问不同表格中的内容控件复选框

时间:2015-01-27 19:01:08

标签: vba ms-word word-vba

我的文档中有多个表格(如附图中所示),因此我尝试仅验证“完成”列中状态的字段,未选中的字段(False)并继续逐一审查。到目前为止,我的主要问题是从那些单元格上的那些特定内容控件中检索值,因为我没有找到方法/函数来执行它。

Table 1 of n

所以到目前为止我的VBA代码(和错误的btw)是这样的,如何检索内部选定单元格内容控件的值的任何范围...(我像初始jk一样在另一个元素内的元素内部,我们需要更深入......)

Public Sub VerifyCheckBox()
Application.ScreenUpdating = False

Dim lastCC As Long, totalRows As Long, nRow As Long
Dim test1 As String
Dim nTbl As Table
Dim thisCell As Range

'lastCC = ActiveDocument.Content.ContentControls.Count
'test1 = ActiveDocument.Content.ContentControls(1).Type = wdContentControlCheckBox
'MsgBox "Found  " & lastCC & "  Content Controls  " & "  First checkbox...  " & test1

For Each nTbl In ActiveDocument.Tables 'Loop Trough the tables in the document
    If nTbl.Cell(nRow, 3).Range = "Complete" Then

        totalRows = nTbl.Rows.Count 'Total number of rows in the selected table

        For nRow = 3 To totalRows
            If nTbl.Cell(nRow, 3).Content.ContentControl.Type = wdContentControlCheckBox And nTbl.Cell(nRow, 3).Content.ContentControl.Checked = False Then
                thisCell = nTbl.Cell(nRow, 3).Range.Select
                MsgBox "Review element:  " & nTbl.Cell(nRow, 1).Range & nTbl.Cell(nRow, 2).Range
            End If
        Next nRow

    End If
    'Debug.Print nTbl.Columns.Count & " " & nTbl.Rows.Count
Next

Application.ScreenUpdating = True
End Sub

非常感谢您的回答

1 个答案:

答案 0 :(得分:1)

泽加德,你非常接近。您可以在下面找到改进的代码,包括一些注释和解释。

Public Sub VerifyCheckBox()


Application.ScreenUpdating = False

Dim lastCC As Long, totalRows As Long, nRow As Long
Dim test1 As String
Dim nTbl As Table
Dim thisCell As Range

For Each nTbl In ActiveDocument.Tables 'Loop Trough the tables in the document

        totalRows = nTbl.Rows.Count 'Total number of rows in the selected table

        'why do you start as of four if your headers are 2nd and data start as of 3rd?
        For nRow = 3 To totalRows
            'you don't need this if you have 'complete' column as a third one
            'you would need something similar if 'complete' could be in different column
            'If nTbl.Cell(nRow, 3).Range = "Complete" Then
        'NEW! let's check first if there is any ContentControl in cell    
        If nTbl.Cell(nRow, 3).Range.ContentControls.Count > 0 Then
            'I assume that you have only one ContentControl per cell
            If nTbl.Cell(nRow, 3).Range.ContentControls(1).Type = wdContentControlCheckBox _
                    And nTbl.Cell(nRow, 3).Range.ContentControls(1).Checked = False Then
                    'if you want to select do it in this way
                    Set thisCell = nTbl.Cell(nRow, 3).Range
                    thisCell.Select
                MsgBox "Review element:  " & nTbl.Cell(nRow, 1).Range & nTbl.Cell(nRow, 2).Range
            End If
            End If
            'End If
        Next nRow


Next

Application.ScreenUpdating = True
End Sub