Excel VBA勾选表单控件复选框复制对应单元格值导出到Word求助
完整实现代码
使用前请先在VBA编辑器依次点击「工具」-「引用」,勾选Microsoft Word [你的版本号] Object Library,否则调用Word对象会报错。
Sub CommandButton1_click() Dim wdApp As Word.Application Dim wdDoc As Word.Document Dim cb As CheckBox Dim arrContent() As String Dim i As Long, j As Long Dim tempStr As String ' 初始化存储内容的数组 ReDim arrContent(0 To 0) ' 遍历当前工作表所有表单控件复选框 For Each cb In ActiveSheet.CheckBoxes ' 判断复选框是否在D6:D122区域、且处于勾选状态 If Not Intersect(cb.TopLeftCell, Range("D6:D122")) Is Nothing And cb.Value = 1 Then ' 存入对应行C列的内容 arrContent(UBound(arrContent)) = Cells(cb.TopLeftCell.Row, "C").Value ReDim Preserve arrContent(0 To UBound(arrContent) + 1) End If Next cb ' 处理空选、移除数组多余空元素 If UBound(arrContent) > 0 Then ReDim Preserve arrContent(0 To UBound(arrContent) - 1) Else MsgBox "未勾选任何行", vbInformation Exit Sub End If ' 冒泡排序实现字母升序,默认不区分大小写 For i = LBound(arrContent) To UBound(arrContent) - 1 For j = i + 1 To UBound(arrContent) If UCase(arrContent(i)) > UCase(arrContent(j)) Then tempStr = arrContent(i) arrContent(i) = arrContent(j) arrContent(j) = tempStr End If Next j Next i ' 生成Word文档并写入内容 Set wdApp = New Word.Application Set wdDoc = wdApp.Documents.Add With wdApp .Visible = True .Activate ' 排序后内容逐行写入Word,可修改vbCrLf调整分隔符 wdDoc.Range.Text = Join(arrContent, vbCrLf) End With ' 释放对象内存 Set wdDoc = Nothing Set wdApp = Nothing Set cb = Nothing End Sub
注意事项
- 如果你使用的是ActiveX控件复选框而非表单控件,需要将遍历逻辑替换为遍历
OLEObjects对象判断控件类型 - 如需区分大小写排序,删除排序判断条件中的
UCase包裹即可 - 如需调整Word中内容的分隔格式,修改
Join函数的第二个参数即可,比如用逗号分隔就改为,
内容的提问来源于stack exchange,提问作者Sonali J
相关产品推荐
相关产品推荐

