|
- Function NameExist(sName As String) As Boolean '判断定义名称是否存在函数
- Dim NameCount As Integer
- NameExist = False
- For NameCount = 1 To Workbooks(1).Names.Count
- If Workbooks(1).Names(NameCount).NameLocal = sName Then
- NameExist = True
- Exit Function
- End If
- Next
- End Function
- Private Sub FindPrint() '判断指定的打印机是否存在
- If Application.ActivePrinter = Evaluate(ActiveWorkbook.Names("printname").Value) Then
- Exit Sub
- Else
- Call Printsetup '调用打印机设置并定义名称
- Exit Sub
- End If
- End Sub
- Private Sub Printsetup() '调用打印机设置并定义名称,把设定的打印机写入Excel名称
- Dim n As Boolean, dyj$
- n = Application.Dialogs(xlDialogPrinterSetup).Show '调用打印机设置
- If n = True Then
- dyj = Application.ActivePrinter
- ActiveWorkbook.Names.Add Name:="printname", RefersTo:=dyj '写入名称
- Exit Sub
- End If
- End Sub
- Private Sub CommandButton1_Click() '打印
- Dim n As Boolean, dyj$
- If NameExist("printname") Then '判断是否有打印机名称定义存在,如没有调用打印机设置
- Dim printyb, duankou, i%, j%
- Call FindPrint '判断指定的打印机是否存在
- Sheet1.PrintOut Application.ActivePrinter = Evaluate(ActiveWorkbook.Names("printname").Value)
- Else
- Call Printsetup '调用打印机设置
- Sheet1.PrintOut Application.ActivePrinter = Evaluate(ActiveWorkbook.Names("printname").Value) '打印Sheet1表格,可自行设定。
- End If
- End Sub
- ********************
- 如果你默认打印机为激光,当打印某表时需用针式打印机
- 可设置以下代码点击按扭时改为针式,打好后又恢复激光
- Sub 在代码中直接写入打印机名()
- Set net = CreateObject("WScript.Network")
- net.SetDefaultPrinter "Jolimark FP-570K"
- ActiveSheet.PrintPreview '打印预览
- net.SetDefaultPrinter "HP LaserJet Professional P 1102w"
- End Sub
- Sub 在工作表中引用打印机名()
- Set net = CreateObject("WScript.Network")
- net.SetDefaultPrinter Range("L1")
- ActiveSheet.PrintPreview '打印预览
- net.SetDefaultPrinter Range("L2")
- End Sub
-
- ***************************
- Private Sub ListBox1_Click()
- Dim i&, s$, ws As Object
- For i = 0 To ListBox1.ListCount - 1
- If ListBox1.Selected(i) = True Then
- s = ListBox1.List(ListBox1.ListIndex, 0)
- End If
- Next
- Set ws = CreateObject("wscript.network")
- ws.SetDefaultPrinter s
- End Sub
- '===============窗体初始化生成打印机列表
- Private Sub UserForm_Initialize()
- Dim i&, ws As Object, ptn$, arr() As String, n&, m&
- Set ws = CreateObject("wscript.network")
- n = ws.EnumPrinterConnections.Count
- ReDim arr(1 To n / 2)
- For i = 1 To n - 1 Step 2
- ptn = ws.EnumPrinterConnections.Item(i) '打印机名称
- m = (i - 1) / 2 + 1
- arr(m) = ptn
- Next
- Me.ListBox1.List = Application.Transpose(arr)
- End Sub
- '====================打印
- Private Sub CommandButton1_Click()
- Dim i&, a&, b&, s$
- For i = 0 To ListBox1.ListCount - 1
- If ListBox1.Selected(i) = True Then
- ' s = ListBox1.List(ListBox1.ListIndex, 0)
- a = 1
- b = Range("d7")
- For i = a To b
- Range("A1:D10").PrintOut
- Range("h2") = Range("h1") + i
- Next
- Else
- MsgBox "请先选择打印机型号"
- End If
- Next
- End Sub
复制代码 |
|