Print Word(.doc) with VB

  • 15 years ago

    I am finishing up a function in a project that writes out variables to a word document, then saves the final product in a relevant directory.  I would like to add a function to print this final paper work.  Is there a print function with in the ADO word object(like a objDoc.Print)?  I would prefer to do it in the object section so that I can print multiple copies as the code updates the form, and only archive the final sheet.  Example of where I would like to place is below.

    Private Sub PWorkFunc()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        Dim aStory As Range
        Dim aField As Field
                   
        Set objWord = New Word.Application
        Set objDoc = New Word.Document
        Set objDoc = objWord.Documents.Open("PathToFile.doc")

        objDoc.Variables("xxx").Value = ."xxx"
     
        For Each aStory In objDoc.StoryRanges
            For Each aField In aStory.Fields
                aField.Update
            Next aField
        Next aStory
       
        '* Add print code here *

        objDoc.SaveAs (."NewFile.doc")
        objDoc.Close False
        objWord.Quit False
    End Sub


























  • 15 years ago

    Hi Trilarian,

    I dont know if this is the sort of thing you wanted but I found an example for you of how this can be done using the Shell API and it seems to work:

    Option Explicit
    Private Const SW_HIDE = 0
    Private Const SW_SHOWDEFAULT = 10
    Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
    Private Declare Function GetActiveWindow Lib "user32" () As Long   'Replace with Me.Hwnd in VB

    Function ShellEx(ByVal sFilePath As String, Optional sVerb As String = "OPEN", Optional lShow As Long = SW_SHOWDEFAULT, Optional sStartDir As String = "") As Long
        Const clMaxStringLen As Long = 260
        On Error Resume Next
        If Len(Dir$(sStartDir)) = 0 Or Len(sStartDir) = 0 And Left$(sFilePath, 7) <> "mailto:" Then
            sStartDir = CurDir$
        End If
        If Len(sFilePath) > clMaxStringLen Then
            'Check the file path length. If exceed max. limit will get a GPF.
            sFilePath = Left$(sFilePath, clMaxStringLen - 3)
            sFilePath = sFilePath & "..."
        End If
        ShellEx = ShellExecute(GetActiveWindow, sVerb, sFilePath, vbNullString, sStartDir, lShow)
    End Function

    Function GetShellError(lErrorCode As Long) As String
        Const SE_ERR_FNF = 2&, SE_ERR_PNF = 3&
        Const SE_ERR_ACCESSDENIED = 5&, SE_ERR_OOM = 8&
        Const SE_ERR_DLLNOTFOUND = 32&, SE_ERR_SHARE = 26&
        Const SE_ERR_ASSOCINCOMPLETE = 27&, SE_ERR_DDETIMEOUT = 28&
        Const SE_ERR_DDEFAIL = 29&, SE_ERR_DDEBUSY = 30&
        Const SE_ERR_NOASSOC = 31&, ERROR_BAD_FORMAT = 11&
        Select Case lErrorCode
            Case SE_ERR_FNF
                GetShellError = "File not found"
            Case SE_ERR_PNF
                GetShellError = "Path not found"
            Case SE_ERR_ACCESSDENIED
                GetShellError = "Access denied"
            Case SE_ERR_OOM
                GetShellError = "Out of memory"
            Case SE_ERR_DLLNOTFOUND
                GetShellError = "DLL not found"
            Case SE_ERR_SHARE
                GetShellError = "A sharing violation occurred"
            Case SE_ERR_ASSOCINCOMPLETE
                GetShellError = "Incomplete or invalid file association"
            Case SE_ERR_DDETIMEOUT
                GetShellError = "DDE Time out"
            Case SE_ERR_DDEFAIL
                GetShellError = "DDE transaction failed"
            Case SE_ERR_DDEBUSY
                GetShellError = "DDE busy"
            Case SE_ERR_NOASSOC
                GetShellError = "No association for file extension"
            Case ERROR_BAD_FORMAT
                GetShellError = "Invalid EXE file or error in EXE image"
            Case Else
                GetShellError = "Unknown error"
        End Select
    End Function

    Private Sub PWorkFunc()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        Dim aStory As Range
        Dim aField As Field
                   
        Set objWord = New Word.Application
        Set objDoc = New Word.Document
        Set objDoc = objWord.Documents.Open("PathToFile.doc")

        objDoc.Variables("xxx").Value = ."xxx"
     
        For Each aStory In objDoc.StoryRanges
            For Each aField In aStory.Fields
                aField.Update
            Next aField
        Next aStory
        objDoc.SaveAs (."NewFile.doc")
        objDoc.Close False
        objWord.Quit False
       Dim lRet As Long
       lRet = ShellEx("C:\Yourfilename.doc", "PRINT", SW_HIDE)
        If lRet < 32 Then
             Debug.Print GetShellError(lRet)
        End If
    End Sub





















































































  • 15 years ago
    /bow Sync

    Thanks!  You are a life saver.  This particular problem was hard to research since 'word', 'microsoft', and 'print' are such common words. 

    I do have a question with this function, but this it is really cosmetic and not a big concern.  Is there a way to force Word to open minimized when it prints?  If it would involve too much(like hooking the application) then don't worry about it.  If it is as simple as adding a 'vbMinimizedNoFocus' to a line of code then please let me know.

    Thanks again.
    -Tril








  • 15 years ago

    Hi Tril,

    Try adding the following declaration:

    Private Const SWSHOWMINIMIZED = 2

    And call the function using this line instead:

    lRet = ShellEx("C:\Yourfilename.doc", "PRINT", SW
    SHOWMINIMIZED)

    Looking at it I guess this simply equates to:

    lRet = ShellEx("C:\Yourfilename.doc", "PRINT", 2)
    If for any reason this doesn't work try 7 (SHOWMINNOACTIVE)

    Bob
















  • 15 years ago
    Thanks Bob for the reply.  It did not work, but I don't think the problem lies in your printing code.  When the fields are updated, word pops up and shows the fields changing.  So when the print command is issued the document is already visable.  It works just fine and the quick flashing of the word document to the screen is not that big a deal.  Thanks for the help.

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” - Brian Kernighan