我正在将输入到 Excel 工作表中的信息转换为 Word 文档。我在 Excel 中有一个“是/否”选择部分,当我运行该程序时,该结果将发送到 Word 中的某个位置。我希望在此阶段将其更改为复选框。我当前的代码是:
Option Explicit
Sub ReplaceText()
Dim wApp As Object, wDoc As Object, rngMap As Range, rw As Range, wsData As Worksheet
Dim res As Boolean, token As String, txt
Set wApp = CreateObject(Class:="Word.Application") 'using an open Word document for testing....
wApp.Visible = True
'Set wDoc = wApp.Documents(1)
Set wDoc = wApp.Documents.Add(Template:="FILELOCATION", NewTemplate:=False, DocumentType:=0)
Set wsData = ThisWorkbook.Worksheets("Form Entry")
'reference mapping table
Set rngMap = ThisWorkbook.Worksheets("Mapping").ListObjects(1).DataBodyRange
For Each rw In rngMap.Rows
token = rw.Cells(1).Value 'placeholder to be replaced
txt = wsData.Range(rw.Cells(2).Value).Value 'value to replace with
res = ReplaceToken(wDoc, token, txt)
rw.Interior.Color = IIf(res, vbGreen, vbRed) 'flag succeed/fail
Next rw
End Sub
'In word document `doc`, replace `<token>` with `txt`
'Return true/false depending on whether a replacement was made
Function ReplaceToken(doc As Object, token As String, txt) As Boolean
Const wdReplaceAll = 2 'define Word constant
Dim rng As Object
Set rng = doc.Content
ReplaceToken = rng.Find.Execute(FindText:="<" & token & ">", _
ReplaceWith:=txt, _
Replace:=wdReplaceAll)
End Function
我想我知道如何使用 VBA 创建复选框,但不知道如何使它们从单元格转换并从 Excel 传输到 Word。
ReplaceToken 函数的修改版本以包含以下逻辑:
函数 ReplaceToken(doc As Object, token As String, txt) As Boolean const wdReplaceAll = 2 '定义Word常量 调暗对象 设置 rng = doc.Content 暗淡替换文本作为字符串
If txt = "Yes" Then
replaceText = "☑" ' Checked box symbol
ElseIf txt = "No" Then
replaceText = "☐" ' Unchecked box symbol
Else
replaceText = txt ' Use the original text if not Yes/No
End If
rng.Find.Execute FindText:="<" & token & ">", _
ReplaceWith:=replaceText, _
Replace:=wdReplaceAll
' Determine if a replacement was made by checking if the search was successful
ReplaceToken = rng.Find.Found
结束功能