您现在的位置是:首页 > Excel技巧>将excel单元格内容及公式添加到Word中

word文字粘贴到excel合并单元格中-将excel单元格内容及公式添加到Word中

发布于2022-04-150人已围观

有时我们需要把指定的单元格或区域中内容导出的Word,同时希望把公式也添加到Word中。方便编写文档

下面自定义VBA函数代码可以实现这个功能,可以将选择的单元格或区域中的公式内容添加到Word中,方便打印。


在VBE模块中添加以下代码,按F5或者运行此代码即可

Public Sub PrintFormulasToWord()
    Dim Cnt As String
    Dim C As Range
    Dim WordObj As Word.Application
    Dim HasArr As Boolean
    On Error Resume Next
    err.Number = 0
    Set WordObj = GetObject(, "Word.Application")
    If err.Number = 429 Then
        Set WordObj = CreateObject("Word.Application")
        err.Number = 0
    End If
    WordObj.Visible = True
    WordObj.Documents.Add
    With WordObj.Selection
        .Font.Name = "Courier New"
        .TypeText "工作表名称:" + ActiveSheet.Name
        .TypeParagraph
        .TypeText "单元格: " + Selection.Cells(1, 1).Address(False, False, xlA1) & " to " & Selection.Cells(Selection.Rows.count, Selection.Columns.count).Address(False, False, xlA1)
        .TypeParagraph
        .TypeParagraph
    End With
    For Each C In Selection
        HasArr = C.HasArray
        Cnt = C.Formula
        If HasArr Then
            Cnt = "{" + Cnt + "}"
        End If
        If Cnt <> "" Then
            With WordObj.Selection
                .Font.Bold = True
                .TypeText C.Address(False, False, xlA1) & ": "
                .Font.Bold = False
                .TypeText Cnt
                .TypeParagraph
                .TypeParagraph
            End With
        End If
    Next C
    MsgBox "已完成将指定单元格公式打印到Word中。 ", , "打印公式到Word"
End Sub


注意:需要单击菜单“工具→引用”,引用“Microsoft Word 14.0 Object Library ”库

word文字粘贴到excel合并单元格中


导出效果图

word文字粘贴到excel合并单元格中

相关文章

文章评论

表情

共0条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~

标签云

站长特荐