I am trying to send raw data (ZPL) to a selected printer in Excel VBA. I have done this successfully in different Ms Access projects, but now I need the same functionality in an Excel project. I am able to use the same code by referencing the Access object library in my Excel VBA project and it works as expected. The problem is that the workbook can later be used on computers without Access installed, and I can't find the alternative objects.
Private Type DocInfo
pDocName As String
pOutputFile As String
pDatatype As String
End Type
Private Declare PtrSafe Function ClosePrinter Lib "winspool.drv" (ByVal _
hPrinter As Long) As Long
Private Declare PtrSafe Function EndDocPrinter Lib "winspool.drv" (ByVal
_
hPrinter As Long) As Long
Private Declare PtrSafe Function EndPagePrinter Lib "winspool.drv" (ByVal
_
hPrinter As Long) As Long
Private Declare PtrSafe Function OpenPrinter Lib "winspool.drv" Alias _
"OpenPrinterA" (ByVal pPrinterName As String, phPrinter As Long, _
ByVal pDefault As Long) As Long
Private Declare PtrSafe Function StartDocPrinter Lib "winspool.drv" Alias
_
"StartDocPrinterA" (ByVal hPrinter As Long, ByVal Level As Long, _
pDocInfo As DocInfo) As Long
Private Declare PtrSafe Function StartPagePrinter Lib "winspool.drv" (ByVal _
hPrinter As Long) As Long
Private Declare PtrSafe Function WritePrinter Lib "winspool.drv" (ByVal _
hPrinter As Long, pBuf As Any, ByVal cdBuf As Long, _
pcWritten As Long) As Long
Public Function RawPrint(strData As String, ByVal SelectedPrinter As String)
Dim defprt As Printer
Dim lhPrinter As Long
Dim lReturn As Long
Dim lpcWritten As Long
Dim lDoc As Long
Dim sWrittenData As String
Dim mDocInfo As DocInfo
lReturn = OpenPrinter(SelectedPrinter, lhPrinter, 0)
If lReturn = 0 Then
MsgBox "The Printer is not recognized."
Exit Function
End If
mDocInfo.pDocName = "ZPl"
mDocInfo.pOutputFile = vbNullString
mDocInfo.pDatatype = vbNullString
lDoc = StartDocPrinter(lhPrinter, 1, mDocInfo)
Call StartPagePrinter(lhPrinter)
sWrittenData = strData
lReturn = WritePrinter(lhPrinter, ByVal sWrittenData, _
Len(sWrittenData), lpcWritten)
lReturn = EndPagePrinter(lhPrinter)
lReturn = EndDocPrinter(lhPrinter)
lReturn = ClosePrinter(lhPrinter)
Exit_RawPrint:
Exit Function
End Function
Without the Access Object Library referenced, I am getting error on "Dim defprt As Printer" - there seems to be no such object as Printer in the Excel object library. Is there any alternative way to access the printers in Excel? Any pointers in that direction would be very helpful. Thanks for your time.