【问题标题】:Copy cell value based on checkbox and export into word根据复选框复制单元格值并导出为word
【发布时间】:2021-06-04 12:20:20
【问题描述】:

我正在尝试创建一个 VBA 脚本,当相应行中的表单控件复选框被“选中”时复制单元格值。大约有 116 行,我只想复制选中行的单元格值。

例如,我的复选框位于单元格 D6:D122 中。如果选中 D6、D8 和 D10 行,我想复制单元格 C6、C8 和 C10 中的值,按字母顺序排列结果并在单击命令按钮时将它们粘贴到新生成的 Word 文档中。我已经知道如何生成一个新的 word 文档,但是我无法复制单元格值并按字母顺序排列它们。

这是我现在的代码:

Sub CommandButton1_click()
Dim wdApp As Word.Application
Dim var as Variant

Set wdApp = New Word.Application
With wdApp
    .Visible = True
    .Activate
    .Documents.Add
End With
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    一种更简单的解决方案:

    Sub CommandButton1_click()
        Dim cl As Range, txt As String
        
        For Each cl In ThisWorkbook.Worksheets(1).Range("D6:D122")
            If cl Then txt = txt & vbLf & cl.Offset(0, -1)
        Next cl
        
        If Len(txt) > 0 Then    ' show Word if you have something to output
            Dim wdApp As New Word.Application   ' declare and create object at once
            With wdApp
                .Documents.Add  ' the added document automatically becomes active
                .Selection.TypeText Mid(txt, 2)   'remove extra (lead) vbLf and output text to Word
                .ActiveDocument.Range.Sort
                .Visible = True 'show Word after processing to improve performance
            End With
        Else
            MsgBox "There is nothing to output", vbInformation + vbOKOnly
        End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-10
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 2015-04-28
      • 2017-01-28
      相关资源
      最近更新 更多