问题
This is a continuation from a previous post of mine: How to select a printer for entire job?, where I basically want to print a series of reports from a form in my Access database.
Which refers to this help doc: https://msdn.microsoft.com/en-us/library/ee336132(v=office.12).aspx
I'm trying to create the combobox with active printers in it in order to temporarily change the default printer for a series of documents. I'm tripped up on where it says "pass a reference to a ComboBox control"... How does one implement this?
Here's the code I have so far, where cboPrinterSelect
is the combobox name:
Private Sub cboPrinterSelect_Load(Cancel As Integer)
Call GetPrinterList
' I'm not sure about this next part either'
cboPrinterSelect.Value = GetPrinterList.value
End Sub
'***************************************************
Private Sub cboPrinterSelect_AfterUpdate(Cancel As Integer)
Set Application.Printer = Application.Printers(cboPrinterSelect.ListIndex)
End Sub
'***************************************************
Private Sub GetPrinterList(ctl As Control)
Dim prt As Printer
For Each prt In Printers
ctl.AddItem prt.DeviceName
Next prt
ctl = Application.Printer.DeviceName
End Sub
Any help/advice would be appreciated.
EDIT:
Here is my updated code, which is still throwing an error (described in Andre's comments):
Private Sub Form_Load()
Call GetPrinterList(Me.cboPrinterSelect)
End Sub
'*********************************************************
Private Sub cboPrinterSelect_AfterUpdate(Cancel As Integer)
Set Application.Printer = Application.Printers(cboPrinterSelect.ListIndex)
End Sub
'***************************************************************
Private Sub GetPrinterList(ctl As Control)
Dim prt As Printer
For Each prt In Printers
ctl.AddItem prt.DeviceName
Next prt
ctl = Application.Printer.DeviceName
End Sub
回答1:
The first part, the call of GetPrinterList()
, must go into the On Load
event of the form.
Private Sub Form_Load()
Call GetPrinterList(Me.cboPrinterSelect)
End Sub
That should be all that's missing.
The default printer is pre-selected by this line:
ctl = Application.Printer.DeviceName
And make sure that cboPrinterSelect has a RowSourceType of Value List.
回答2:
Try the following code, it will display all connected Printers in the combo_box in your User_Form.
Public Sub GetPrinters()
' Use a large array (supports up to 100 printers).
ReDim result(100) As String
Dim wshNetwork, allPrinters As Object
' Get the network object
Set wshNetwork = CreateObject("WScript.Network")
Set allPrinters = wshNetwork.EnumPrinterConnections
' Printers collection has two elements for each printer.
For i = 0 To allPrinters.Count - 1 Step 2
Print_Series.cboPrinterSelect.AddItem allPrinters.Item(i + 1)
Next
' call your user form and combo box will have all active printers
Print_Series.Show
End Sub
来源:https://stackoverflow.com/questions/38330111/how-to-pass-reference-to-combobox