2011年6月2日 星期四

VBA 中 Excel Sheet 在指定 Printer中 列印

Public Sub userDefinePrint(sh As Worksheet, sharePath As String, shareName As String, printerName As String)
TryAgain:
On Error Resume Next

Dim printerFullName As String
printerFullName = NetworkPrinter(sharePath & "\" & printerName)


ActivePrinter = printerFullName

If Err.Number <> 0 Then
PrintServer = sharePath & "\" & shareName

Set objNetwork = CreateObject("Wscript.Network")
objNetwork.AddWindowsPrinterConnection (PrintServer)
GoTo TryAgain
End If

With sh.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0)
.BottomMargin = Application.InchesToPoints(0)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
.PaperSize = 234
End With

If Err.Number <> 0 Then
sh.PrintOut Copies:=1, Preview:=False, ActivePrinter:=printerFullName, Collate:=True
Else
sh.PrintOut Copies:=1, Preview:=False, ActivePrinter:=printerFullName, Collate:=True
End If


End Sub

Public Function NetworkPrinter(ByVal myprinter As String)
On Error Resume Next
Dim NetWork As Variant
Dim X As Integer
Dim Prt_On As String
Prt_On = " on "
'/// Define NetWork Array \\\
NetWork = Array("Ne00:", "Ne01:", "Ne02:", "Ne03:", "Ne04:", _
"Ne05:", "Ne06:", "Ne07:", "Ne08:", _
"Ne09:", "Ne10:", "Ne11:", "Ne12:", _
"Ne13:", "Ne14:", "Ne15:", "Ne16:", _
"LPT1:", "LPT2:", "File:", "SMC100:")
'Setup printer to Print
X = 0
TryAgain:
On Error Resume Next
'Printer
Application.ActivePrinter = myprinter & Prt_On & NetWork(X)
If Err.Number <> 0 And X < 16 Then     X = X + 1     GoTo TryAgain   ElseIf Err.Number <> 0 And X > 15 Then
GoTo PrtError
End If
On Error GoTo 0
NetworkPrinter = myprinter & Prt_On & NetWork(X)
errorExit:
Exit Function
PrtError:
'no printer found
NetworkPrinter = ""
Resume errorExit
End Function

沒有留言:

張貼留言