如何将excel公式打印到Word中
- 2023-03-01
- 来源/作者: Wps Office教程网/ 菜鸟图库
- 129 次浏览
有时我们需要将指定单元格或区域中的公式打印出来,以便分析。下面的VBA代码可以实现这个功能,可以将选择的单元格或区域中的公式打印到Word中,方便打印。
使用方法:
1.单击菜单“工具→引用”,在弹出的“引用 VBAproject”窗口中,勾选“Microsoft Word 11.0 Object Library ”
2.在VBA编辑器中,单击菜单“插入→模块”,在右侧的代码窗口中输入下列代码。
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
3.在工作表中选择需要打印的区域,回到VBA编辑器中,运行代码。