开发者

Access: Word automation Headers and footers

开发者 https://www.devze.com 2023-03-15 20:25 出处:网络
I am using Access to send text to Word via bookmarks. I have bookmarks in headers and footers, but when I try to send the text to it get the error: “Word cannot find the requested bookmark.”

I am using Access to send text to Word via bookmarks. I have bookmarks in headers and footers, but when I try to send the text to it get the error: “Word cannot find the requested bookmark.

I am using the following code to send text to Access

' Create a Word document from template.
Dim WordApp As Word.Application
Dim strTemplateLocation As String
Dim myVariable = “TEST!!”

' Specify location of template
strTemplateLocation = Left(CurrentDb.Name, InStrRev(CurrentDb.Name, "\")) & "test.dot"

Set WordApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
    Set WordApp = CreateObject("Word.Application")
End If

WordApp.Visible = T开发者_StackOverflow中文版rue
WordApp.WindowState = wdWindowStateMaximize
WordApp.Documents.Add Template:=strTemplateLocation, NewTemplate:=False


' Replace each bookmark with field contents.
WordApp.Selection.GoTo what:=wdGoToBookmark, Name:="myBookmark"
WordApp.Selection.TypeText myVariable

DoEvents
WordApp.Activate
Set WordApp = Nothing

I am using Office 2003 file formats.


First, you have to make sure that every Word bookmark is unique. We use Access as an automation engine for Word all the time, and this can be an easy mistake. If in doubt, delete your bookmark in your Word template and put it back in.

Here is some code to get you on your way. Let's start by declaring some variables, specifically a Word Document to go with your Word Application, as objects since you're late binding.

Dim WordApp As Object
Dim objDoc As Object

or, if you can early bind...

Dim WordApp As Word.Application
Dim objDoc As Word.Document

Next, you know how to get set your WordApp object, but I would set my document object to give me more flexibility.

Set objDoc = WordApp.Documents.Add Template:=strTemplateLocation, NewTemplate:=False

I usually have this next section in a sub routine which I just pass in the bookmark name and value as strings. Again, you can send the same variable to as many bookmarks as you would like, but you have to have unique bookmark names in your Word template.

If objDoc.Bookmarks.Exists(sBookmark) = True Then

    objDoc.Bookmarks(sBookmark).SELECT
    WordApp.Selection = sValue

End If

Then you seemed to have some trouble with how you found Word when you opened it up. I prefer to set things back to 'normal' if there is such a thing. :)

With WordApp

    If .ActiveWindow.View.SplitSpecial <> 0 Then
        .ActiveWindow.Panes(2).Close
    End If

    If .ActiveWindow.ActivePane.View.Type = 1 Or .ActiveWindow.ActivePane.View.Type = 2 Then
        .ActiveWindow.ActivePane.View.Type = 3
    End If

    .ActiveWindow.ActivePane.View.SeekView = 0

End With
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号