摘要

借助自动化,你几乎可以在 Word 中以编程方式执行用户可手动Microsoft Office操作。 但是,如果要输入大量文本并设置格式,可能需要大量代码。 如果可以将数据表示为 RTF (格式) 格式,则经常可以减少自动化代码。 可以创建 RTF 字符串,将 RTF 字符串复制到剪贴板,然后将 RTF 字符串粘贴到文档中。本文介绍如何构建一个简单的示例,Visual Basic Word、创建新文档,以及使用预建 RTF 字符串向文档添加一些格式文本。

更多信息

若要创建示例项目,请执行以下步骤:

  1. 启动Visual Basic,然后创建新的 Standard EXE。 默认情况下,将创建名为 Form1 的窗体。

  2. 将 CommandButton 添加到窗体,双击 CommandButton,然后将以下代码添加到 Click 事件。

    'sRTF represents the rich-text-formatted string to paste into WordDim sRTF As StringsRTF = "{\rtf1\ansi\ansicpg1252\deff0\deftab720{\fonttbl" & _       "{\f0\fswiss MS Sans Serif;}{\f1\froman\fcharset2 Symbol;}" & _       "{\f2\froman\fprq2 Times New Roman;}}" & _       "{\colortbl\red0\green0\blue0;\red255\green0\blue0;}" & _       "\deflang1033\horzdoc{\*\fchars }{\*\lchars }" & _       "\pard\plain\f2\fs24 Line 1 of \plain\f2\fs24\cf1" & _       "inserted\plain\f2\fs24  file.\par }"'Copy the contents of the Rich Text to the clipboardDim lSuccess As LongDim lRTF As LongDim hGlobal As LongDim lpString As LonglSuccess = OpenClipboard(Me.hwnd)lRTF = RegisterClipboardFormat("Rich Text Format")lSuccess = EmptyClipboardhGlobal = GlobalAlloc(GMEM_MOVEABLE Or GMEM_DDESHARE, Len(sRTF))lpString = GlobalLock(hGlobal)CopyMemory lpString, ByVal sRTF, Len(sRTF)GlobalUnlock hGlobalSetClipboardData lRTF, hGlobalCloseClipboardGlobalFree hGlobal'Paste into a new Word documentDim oWord As ObjectDim oDoc As ObjectSet oWord = CreateObject("word.application")Set oDoc = oWord.Documents.AddoWord.Selection.PasteoWord.Visible = True
  3. 将以下代码添加到窗体模块的"常规声明"部分。

    Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As LongPrivate Declare Function RegisterClipboardFormat Lib "user32" Alias _    "RegisterClipboardFormatA" (ByVal lpString As String) As LongPrivate Declare Function EmptyClipboard Lib "user32" () As LongPrivate Declare Function CloseClipboard Lib "user32" () As LongPrivate Declare Function SetClipboardData Lib "user32" ( _    ByVal wFormat As Long, ByVal hMem As Long) As LongPrivate Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _    ByVal dwBytes As Long) As LongPrivate Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _    ByVal Destination As Long, Source As Any, ByVal Length As Long)Private Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As LongPrivate Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As LongPrivate Declare Function GlobalFree Lib "kernel32" Alias "GlobalFree" ( _     ByVal hMem As Long) As LongPrivate Const GMEM_DDESHARE = &H2000Private Const GMEM_MOVEABLE = &H2
  4. 按 F5 键运行项目。 Word 将启动,然后创建一个包含带格式文本的新文档。

参考

有关开发解决方案和解决方案Office,请访问以下 Microsoft 网站:

http://support.microsoft.com/ofdhttp://msdn.microsoft.com/office

需要更多帮助?

需要更多选项?

了解订阅权益、浏览培训课程、了解如何保护设备等。