使用 vba 将格式化文本复制到访问中

copy formatted text into access using vba

我需要将 Word 中的格式化文本保存到 Access 数据库中。

到目前为止,我已经设法弄清楚如何在访问字段中存储格式化文本(在 Table 中创建一个备注字段并将文本格式设置为富文本格式)。搜索所以我还没有找到关于如何将所述文本从 word 传输到 Access 的解决方案。

我知道这是可能的,因为如果您手动操作,只需复制和粘贴信息即可。

我的问题是,如何使用 VBA 将格式化文本从 word 复制到 table 的字段中?

实验性地,我创建了以下内容来对此进行测试。到目前为止没有成功...

Sub GetComments()
'Imports Analyst Comments from Excel files als OLE Objects.
'---------------------------------

'Access Variables
Dim dbsFundDB As DAO.Database
Dim rsComments As DAO.Recordset

Set dbsFundDB = CurrentDb
Set rsComments = dbsFundDB.OpenRecordset("tblFunds")

'Word Variables
Dim doc             As Word.Application
Dim dcmt            As Word.Document
Dim sectn           As Word.Section
Dim obCommentText   As Object
Dim sAnalystText    As String

'Open New Word File
Set doc = New Word.Application
doc.Visible = True
Set dcmt = doc.Documents.Open(sPathTemplate)
Set sectn = dcmt.Sections(1)

sectn.Range.Select
Selection.InsertFile FileName:="myfile.rtf", Range:="", _
  ConfirmConversions:=False, Link:=False, Attachment:=False

sAnalystText = sectn.Range.Tables(1).cell(1, 1).Range.FormattedText

rsComments.AddNew
rsComments![Long Comment Exec] = sAnalystText
rsComments.Update

sectn.Range.Select
dcmt.Close savechanges:=False
doc.Quit

End Sub

更新 我尝试实施 Matt Hall 的回答。虽然文本确实被复制到数据库,但它还没有保留格式:

这是我作为简单测试的实现:

Option Explicit
Public Const sPathTemplate As String = "W:\L\BDTP\Products\FundResearchTool\Advisory.docx"
Option Compare Database

Sub GetComments()
'Imports Comments from word and save in DB
'Test soubroutine
'---------------------------------

'Word Variables
Dim obCommentText As Variant
Dim strSQL As String

obCommentText = GetWordContent(sPathTemplate)

strSQL = "insert into [tblText]([TestField]) values('" & obCommentText & "')"

DoCmd.RunSQL strSQL
MsgBox "Import Successful", vbInformation Or vbOKOnly

End Sub
Private Function GetWordContent(strFile As String) As Variant

    ' This function takes the path obtained to the MS-Word Document selected in
    ' the FileToOpen function and then uses that to open that MS-Word Document
    ' and retrieve its text contents

    Dim objDoc As Word.Document

    Set objDoc = GetObject(strFile)

    GetWordContent = CVar(objDoc.Sections(1).Range.Text)

    objDoc.Close

End Function

这是一个大量引用this.

的方法

在开始之前,请确保在 VBA 编辑器 > 工具 > 参考中勾选了这些(或您的 Access 版本的等效)参考:

Microsoft Word 15.0 Object Library

Microsoft Office 15.0 Object Library

假设您已经设置了一个带有命令按钮的表单来触发此 MS-Word 导入,请将以下函数和子例程放在该表单的 VBA 模块中的某个位置:

1) 文件选择器功能:

这将允许您 select 使用您在整个 Windows 中看到的熟悉的旧文件对话 window 想要使用的 MS-Word 文档。最终,它所做的只是保存您在 (2) 中描述的子例程中选择使用的文件的文件路径和名称...

Private Function FileToOpen() As String

    ' This function will essentially allow you to browse to MS-Word document
    ' and then store the path of that file for use in the GetWordContent function

    Dim fDialog As Office.FileDialog
    Dim varFile As Variant

    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

    With fDialog

        .AllowMultiSelect = False
        .Title = "Select Word document to import"
        .Filters.Clear
        .Filters.Add "Word files", "*.doc?"

        If _
            .Show = True _
        Then
            For Each varFile In .SelectedItems

                FileToOpen = varFile

            Next

        Else

            FileToOpen = ""

        End If

    End With

End Function

2)获取MS-Word文档格式化文本内容子程序:

此子例程将使用 MS-Word 文档的文件路径和名称 selected 在文件选择器功能(以上)中打开 MS-Word 文档,select 所有文本,将其复制到剪贴板,将其粘贴到 Access 中打开的表单的文本框中,然后关闭 MS-Word...

Private Sub GetWordContent(strFile As String)

    ' This function takes the path obtained to the MS-Word Document selected in
    ' the FileToOpen function and then uses that to open that MS-Word Document
    ' and retrieve its text contents and paste them in to WordDocData textbox on
    ' the currently open form in Access

    ' Create an MS-Word Object:

    Dim objDoc As Object
    Set objDoc = CreateObject("Word.Application")

    ' Open the file selected in FileToOpen() and copy the contents to clipboard:

    With objDoc

        .Documents.Open strFile
        .Visible = True
        .Activate
        .Selection.WholeStory
        .Selection.Copy

    End With

    ' Set the focus to the WordDocData textbox on the Access Form and paste clipboard:

    Me.WordDocData.SetFocus
    DoCmd.RunCommand acCmdPaste

    Me.WordDocDataSrc = strFile

    ' Save record on the form:

    If _
        Me.Dirty _
    Then

        Me.Dirty = False

    End If

    ' A bit hacky this bit. When you close MS-Word after copying a lot of data,
    ' you might get a message asking you if you if you want to keep the last item
    ' you copied. This essentially overwrites the clipboard that currently has
    ' the whole document stored, to just the first 5 characters, which should allow
    ' MS-Word to be closed here without a pop-up message to deal with:

    With objDoc

        .Selection.HomeKey Unit:=wdLine
        .Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
        .Selection.Copy
        .Documents.Close
        .Quit

    End With

    Set objDoc = Nothing

End Sub

您的命令按钮的点击事件:

这个子例程应该 运行 来自命令按钮的单击事件。它本质上是调用 FileToOpen 函数和 GetWordContent 子例程,以便用户 select 一个 MS-Word 文档,然后让 VBA 从MS-Word 文档到 Access 中打开的表单上的富文本备忘录文本框。

请注意,此子例程进行了一些假设,并引用了 controls/tables/fields 的名称以及您可能尚未设置的诸如此类的东西。这些假设是:

  1. 您的表单命令按钮名为 cmdGetWordData
  2. 您的 Access 数据库有一个 table 名为 tblWordDump
  3. 您的表单已绑定到 table tblWordDump
  4. tblWordDump 有 2 个备忘录文本字段,分别称为 WordDocDataSrcWordDocData,用于存储导入的文件 path/name 和文本内容两者都已添加到您的表单中
Private Sub cmdGetWordData_Click()

    ' This subroutine runs on your command button; it will call both the FileToOpen function and GetWordContent subroutine
    ' to retrieve the text contents of your chosen MS-Word Document.
    ' It will then store both the path the text contents of of your chosen MS-Word Document in 2 fields in a table in Access.

    ' NOTE: this code assumes that your Access database has:
    ' - a table called tblWordDump
    ' - a memo text field in this table called WordDocDataSrc to store the path of MS-Word file imported
    ' - a memo text field in this table called WordDocData with the TextFormat property set to "Rich Text",
    '   which will store the text and text formating of the MS-Word file imported

    Dim strFile As String
    Dim strWordContent As Variant

    ' Select file via File Dialogue

    strFile = FileToOpen

    ' Conditionals when a file was or wasn't selected

    If _
        Len(strFile) > 0 _
    Then

        DoCmd.GoToRecord , , acNewRec

        GetWordContent strFile

        MsgBox "Import Successful", vbInformation Or vbOKOnly

    Else

        MsgBox "No File Selected", vbExclamation Or vbOKOnly

    End If

End Sub

Here's an example Access file 供您浏览。