vba - 我正在尝试创建一个简单的用户表单,用于在 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 次,它会像这样分别添加文本块和段落:
文字测试文字测试文字测试
(新段落)
(新段落)
(新段落)
我想要的是这个:
文字测试
(新段落)
文字测试
(新段落)
文字测试
(新段落)
解决方案
回答第一个问题,有足够的信息可以提供答案......
在 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
推荐阅读
- html - Bootstrap 4 将项目放在彼此的弹性框下方
- reactjs - CORS:通过 webpack-dev-server 将 localhost 代理到外部 API
- java - 永久保存用户输入以供以后使用和扩展您的程序
- python - 删除 venv 会删除已安装的模块吗?
- python - 生成相关随机样本
- visual-studio-2019 - VB.Net Visual Studio 2019 社区版中的调试设置
- python - 你可以使用 C# 来编排(持久函数)一个 Python Azure 函数吗?
- python - Python:如何将另一个 df 列的值附加到当前 df col 名称
- javascript - 在 React 组件中使用分页 API
- time-series - 通过从 imputeTS 函数中提取数据来计算时间序列中的平均间隙大小