首页 > 解决方案 > 我正在尝试创建一个简单的用户表单,用于在 Word 中添加和删除文本块

问题描述

我有一个带有一堆复选框的用户表单。如果复选框为真,我希望 VBA 代码添加一个文本块(定义为变量),如果未选中则删除该文本块。例如,这就是我为其中一个复选框所拥有的:

Private Sub CheckBox1_Click()
    Dim Text1 As String
    Text1 = "Text test"
    If CheckBox1.Value = True Then
    Selection.TypeText Text:=Text1
    Selection.InsertParagraph
    End If
    If CheckBox1.Value = False Then
    Selection.Delete Text:=Text1
    End If
End Sub

首先,这Selection.Delete Text:=Text1部分是完全错误的。我试图用谷歌搜索类似的东西,但找不到任何删除变量内容的东西。

其次,代码似乎有错误Selection.InsertParagraph。我希望它在每个文本/变量块之间添加一个新段落,但是按照现在的代码方式,如果我要激活宏 3 次,它会像这样分别添加文本块和段落:

文字测试文字测试文字测试

(新段落)

(新段落)

(新段落)

我想要的是这个:

文字测试

(新段落)

文字测试

(新段落)

文字测试

(新段落)

标签: vbams-word

解决方案


回答第一个问题,有足够的信息可以提供答案......

在 Word 文档中插入和格式化某些内容的最佳控制是使用Range对象。只能有一个选择,但代码可以使用多个范围。

为了在文本之后插入新段落,可以使用 ANSI 13 字符在文本末尾附加新段落,该字符可以在 VBA 代码中使用vbCr.

例子:

Private Sub CheckBox1_Click()
    Dim Text1 As String
    Dim rngTarget as Range

    Text1 = "Text test"
    Set rngTarget = Selection.Range

    If CheckBox1.Value = True Then
      rngTarget.Text = Text1 & vbCr
    End If
    '
    'If CheckBox1.Value = False Then
    '  Selection.Delete Text:=Text1
    'End If

   '''Move to the end of the range and select that for the next iteration
    rngTarget.Collapse wdCollapseEnd
    rngTarget.Select
End Sub

推荐阅读