使用 vb.net 在 word 中选中一个复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14179275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:47:35  来源:igfitidea点击:

check a checkbox in word using vb.net

vb.netms-wordautomation

提问by user1758663

I have a word doc with several checkbox fields. I can fill the text fields, but haven't figured out how to check checkboxes.

我有一个带有多个复选框字段的 word 文档。我可以填写文本字段,但还没有弄清楚如何选中复选框。

I can't just make a macro in word and see how word does it because to use the keyboard to check the box (space bar), you have to enable document protection, which disables macro creation.

我不能只在 word 中创建一个宏,然后看看 word 是如何做到的,因为要使用键盘选中复选框(空格键),您必须启用文档保护,这会禁用宏创建。

采纳答案by Pilgerstorfer Franz

I just tried setting an old fashion Word2003 Checkbox with VBA. Worked with that piece of code:

我只是尝试使用 VBA设置旧式Word2003 复选框。使用那段代码:

' demo purposes - added a command
Private Sub CommandButton1_Click()
    ' FormFields refers to Word2003 FormFields
    If ActiveDocument.FormFields(1).Type = wdFieldFormCheckBox Then
        ActiveDocument.FormFields(1).CheckBox.Value = True
    End If

   ' ContentControls refers to >= Word2007 Controls - thx to StevenDotNet for the hint
   ActiveDocument.ContentControls(1).Checked = True
End Sub

WordCheckBoxControl_Form

WordCheckBoxControl_Form

On the other hand I created a VS2012 WordProject with VB.netand added some code to check the box on load.

另一方面,我用 VB.net创建了一个VS2012 WordProject并添加了一些代码来检查加载时的框。

Private Sub ThisDocument_Open() Handles Me.Open
    Me.FormFields(1).CheckBox.Value = True
End Sub

回答by Steven Liekens

Each checkbox has a Valueproperty. You can set this property to Trueor Falseto check or uncheck the checkbox.

每个复选框都有一个Value属性。您可以将此属性设置为TrueFalse以选中或取消选中该复选框。

EDIT

编辑

I wrote a little macro that ticks all boxes in the active document. You can edit it to suit your needs. VBA is really nasty though, it took me around 15 minutes to figure this out.

我写了一个小宏来勾选活动文档中的所有框。您可以编辑它以满足您的需要。不过,VBA 真的很糟糕,我花了大约 15 分钟才弄明白。

Sub CheckAllBoxes()
    Dim ctrl As ContentControl
    For Each ctrl In ActiveDocument.ContentControls
        If ctrl.Type = wdContentControlCheckBox Then
            ctrl.Checked = True
        End If
    Next
End Sub