有時我們需要將指定單元格或區(qū)域中的公式打印出來,以便分析。下面的VBA代碼可以實現(xiàn)這個功能,可以將選擇的單元格或區(qū)域中的公式打印到Word中,方便打印。
使用方法:
1.單擊菜單“工具→引用”,在彈出的“引用 VBAproject”窗口中,勾選“Microsoft Word 11.0 Object Library ”
2.在VBA編輯器中,單擊菜單“插入→模塊”,在右側(cè)的代碼窗口中輸入下列代碼。
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.在工作表中選擇需要打印的區(qū)域,回到VBA編輯器中,運行代碼。