Excel中的VBA可以控制Word文档中的“内容控制”复选框

时间:2018-12-04 21:25:41

标签: excel vba


我已经研究了许多有关此主题的帖子,下面是我在Excel的标准模块中想出的代码,以尝试完成将Word文档中的内容控制复选框标记为True,但是我似乎缺少一个关键部分代码,并且无法弄清楚是什么代码导致该代码无法执行,并且未选中“控制复选框”。任何帮助将不胜感激。

Private Sub TitleOrder_Click()
    Dim WordApp As Object
    Dim WordDoc As Object
    Dim cc As ContentControl  'Maybe this should this be Dim cc as object instead??"

    ContLoanFile.Hide

    Application.ScreenUpdating = False

    SaveAsName = ThisWorkbook.path & "\Title Order Form - " & Split(wsSI.Range("PBName"))(2) & ".docx"

    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True
    Set WordDoc = WordApp.Documents.Add(Template:="Z:\Title Work Template.docx", NewTemplate:=False, DocumentType:=0)
    Set cc = WordDoc.SelectContentControlsByTag("mpfPlat").Item(1)

    If wsFI.Range("Plat_DrawingYes") = "TRUE" Then
        If cc.Type = wdContentControlCheckBox Then
            cc.Checked = True
        End If
    End If


    WordApp.ActiveDocument.SaveAs FileName:=SaveAsName
    WordApp.Quit
    Set WordApp = Nothing

    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

导致此问题不起作用的问题是由于我如何基于“复选框用户窗体控件”设置单元格值。我以为Cell中的值是一个文本字符串,但是显然不是(不确定为什么),所以一旦我从If wsFI.Range("Plat_DrawingYes")="TRUE"的工作“ TRUE”周围删除了“”,代码就会按预期运行。下面是解决方案。感谢@Tim Williams的帮助。

Private Sub TitleOrder_Click()
    Dim WordApp As Object
    Dim WordDoc As Object
    Dim cc As ContentControl  'Maybe this should this be Dim cc as object instead??"

    ContLoanFile.Hide

    Application.ScreenUpdating = False

    SaveAsName = ThisWorkbook.path & "\Title Order Form - " & Split(wsSI.Range("PBName"))(2) & ".docx"

    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True
    Set WordDoc = WordApp.Documents.Add(Template:="Z:\Title Work Template.docx", NewTemplate:=False, DocumentType:=0)
    Set cc = WordDoc.SelectContentControlsByTag("mpfPlat").Item(1)

    If wsFI.Range("Plat_DrawingYes") = TRUE Then
        If cc.Type = wdContentControlCheckBox Then
            cc.Checked = True
        End If
    End If


    WordApp.ActiveDocument.SaveAs FileName:=SaveAsName
    WordApp.Quit
    Set WordApp = Nothing

    Application.ScreenUpdating = True

End Sub