【问题标题】:Access VBA- insert checkbox after text in Word Table访问 VBA-在 Word 表中的文本后插入复选框
【发布时间】:2017-02-12 16:06:40
【问题描述】:

我的 VBA 会根据条件动态写入多个表,并且运行良好。

例如这里是添加一行,格式化它并前进到下一行。

        oDoc.Tables(t).Rows.Add 'add a row below control number
        oDoc.Tables(t).Rows(i).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
        oDoc.Tables(t).Rows(i).Shading.BackgroundPatternColor = oTableHeaderColor
        i = i + 1 'advance to row below control number row.
        oDoc.Tables(t).Cell(i, 2).Range.Text = "Check Definition"

我这样做是因为我只是不知道任何给定表有多少行 - 所以我根据需要创建行,可能很笨拙但它有效。

我需要做的是在带有这样文本的行中添加一个可勾选的复选框。

计划:☐

我尝试了几种似乎不起作用的方法。据我所知,这是因为我没有创建表格然后选择它。我试过录制一个宏,它只显示了关于选择的部分。

这是我得到的,它会弹出一个错误。

oDoc.Tables(t).Cell(i, 2).Range.Text = "Planned: " & oDoc.Tables(t).Cell(i, 1).Range.ContentControls.Add(wdContentControlCheckBox)

我得到“请求的集合成员不存在。

如果我尝试将它放在两行上,它只会覆盖单元格 1。使用复选框,我似乎无法先将其定位到单元格的末尾。有任何想法吗?我已经尝试过 insertbefore 并且可行,但我必须在同一个单元格中插入几个复选框。

有什么想法吗? 谢谢。

【问题讨论】:

    标签: ms-access ms-word vba


    【解决方案1】:

    将文本 + 复选框 + 其他文本 + 第二个复选框放入一个单元格是很棘手的。

    这可能是您实际上必须使用Selection 对象的少数情况之一。

    这在 Word 中适用于我:

    Dim oDoc As Word.Document
    Set oDoc = ThisDocument
    Const t = 1
    Const i = 1
    
    Dim rng As Word.Range
    Dim iCheck As Long
    Dim sLabel As String
    
    Set rng = oDoc.Tables(t).Cell(i, 2).Range
    rng.Select
    With Selection
        .Collapse Direction:=wdCollapseStart
        For iCheck = 1 To 3
            sLabel = Choose(iCheck, "Planned: ", " Done: ", " Perhaps: ")
    
            .TypeText Text:=sLabel
            .Range.ContentControls.Add wdContentControlCheckBox
            ' move cursor after checkbox
            .MoveRight Unit:=wdCharacter, Count:=2
        Next iCheck
    End With
    

    在 Access 中,请改用 oWord.Selection(或您对 Word 的引用)。

    以下内容适用于单个复选框,但我没有设法在 附加文本之后创建第二个。

    Dim rng As Word.Range
    Set rng = oDoc.Tables(t).Cell(i, 2).Range
    rng.Text = "Planned: "
    ' set range to end of cell
    rng.Collapse Direction:=wdCollapseEnd
    ' I'm not entirely sure why this is needed, but without the checkbox goes into the next cell
    rng.MoveEnd Unit:=wdCharacter, Count:=-1
    rng.ContentControls.Add (wdContentControlCheckBox)
    

    【讨论】:

    • 成功了。我简直不敢相信我之前离它有多近,但该死的你钉了它。我对你的词 vba 所做的只是添加 oWord.Selection 代替选择,我可以添加任意数量的框。
    • 我最终使用它并进行了修改。而不是选择我只是使用 UBound 并拆分它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    相关资源
    最近更新 更多