Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use VB Printer object in VBA

I'm trying to print to an Epson printer using VBA code without success. Using VB6, I have the following code which it works just fine:

Printer.Print "Hello"
Printer.EndDoc 

My problem is that I don't see the Printer object in VBA (using MS Access Macros). Do I have to include a specific reference? If yes, what it would be? such that I have VB6 runtime installed on the same machine.

like image 617
rsleiman Avatar asked Nov 19 '25 23:11

rsleiman


1 Answers

You can't do this from MS Access, but KB154078 shows VBA code that can use the Win32 API to communicate directly with the print spooler and send raw data to a printer:

  Option Explicit

  Private Type DOCINFO
      pDocName As String
      pOutputFile As String
      pDatatype As String
  End Type

  Private Declare Function ClosePrinter Lib "winspool.drv" (ByVal _
     hPrinter As Long) As Long
  Private Declare Function EndDocPrinter Lib "winspool.drv" (ByVal _
     hPrinter As Long) As Long
  Private Declare Function EndPagePrinter Lib "winspool.drv" (ByVal _
     hPrinter As Long) As Long
  Private Declare Function OpenPrinter Lib "winspool.drv" Alias _
     "OpenPrinterA" (ByVal pPrinterName As String, phPrinter As Long, _
      ByVal pDefault As Long) As Long
  Private Declare Function StartDocPrinter Lib "winspool.drv" Alias _
     "StartDocPrinterA" (ByVal hPrinter As Long, ByVal Level As Long, _
     pDocInfo As DOCINFO) As Long
  Private Declare Function StartPagePrinter Lib "winspool.drv" (ByVal _
     hPrinter As Long) As Long
  Private Declare Function WritePrinter Lib "winspool.drv" (ByVal _
     hPrinter As Long, pBuf As Any, ByVal cdBuf As Long,  _
     pcWritten As Long) As Long

  Private Sub Command1_Click()
      Dim lhPrinter As Long
      Dim lReturn As Long
      Dim lpcWritten As Long
      Dim lDoc As Long
      Dim sWrittenData As String
      Dim MyDocInfo As DOCINFO
      lReturn = OpenPrinter(Printer.DeviceName, lhPrinter, 0)
      If lReturn = 0 Then
          MsgBox "The Printer Name you typed wasn't recognized."
          Exit Sub
      End If
      MyDocInfo.pDocName = "AAAAAA"
      MyDocInfo.pOutputFile = vbNullString
      MyDocInfo.pDatatype = vbNullString
      lDoc = StartDocPrinter(lhPrinter, 1, MyDocInfo)
      Call StartPagePrinter(lhPrinter)
      sWrittenData = "How's that for Magic !!!!" & vbFormFeed
      lReturn = WritePrinter(lhPrinter, ByVal sWrittenData, _
         Len(sWrittenData), lpcWritten)
      lReturn = EndPagePrinter(lhPrinter)
      lReturn = EndDocPrinter(lhPrinter)
      lReturn = ClosePrinter(lhPrinter)
  End Sub

Another example is given in KB175083.

like image 158
Renaud Bompuis Avatar answered Nov 21 '25 14:11

Renaud Bompuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!