gpt4 book ai didi

excel - 通过 VBA 设置默认打印机

转载 作者:行者123 更新时间:2023-12-04 20:04:08 25 4
gpt4 key购买 nike

我正在运行一个 Excel 宏,它在两台打印机之间切换,一台名为“RecOffice_Pink”,另一台名为“RecOffice_White”。

这是解决 VBA 无法轻松指定要从中打印的托盘的问题的 hacky 解决方法。粉红色打印机除了一个托盘外,所有托盘都被禁用,其中包含我们的粉红色纸张。

我在用

CreateObject(WScript.Network).SetDefaultPrinter "RecOffice_Pink"
and
CreateObject(WScript.Network).SetDefaultPrinter "RecOffice_White"

这在我们的 Windows 7 计算机上运行良好,但它似乎不适用于我们的任何 Windows 10 PC。

没有抛出错误,没有创建消息,只是似乎没有切换打印机。

我已经尝试将它们设置为我们网络上的共享打印机,在每台计算机上设置它们,这两种方法都可以在 Windows 7 上正常运行。

最佳答案

用法

  SetDefaultPrinter "RecOffice_Pink"


设置默认打印机
 Sub SetDefaultPrinter(PrinterName As String, Optional ComputerName As String = ".")
Dim Printer As Object, Printers As Object, WMIService As Object
Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")
Set Printers = WMIService.ExecQuery("Select * from Win32_Printer Where Name = '" & PrinterName & "'")

For Each Printer In Printers
Printer.SetDefaultPrinter
Next

End Sub

列出新工作簿中的打印机和打印机属性
Sub ListPrinters(Optional ComputerName As String = ".")
Dim WMIService As Object
Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")

Dim Printers As Object
Set Printers = WMIService.ExecQuery("Select * from Win32_Printer")

Dim Printer As Object
Dim Item As Object
Dim Results
Dim r As Long, c As Long, NameIndex As Long
For Each Printer In Printers
ReDim Results(1 To Printers.Count + 1, 1 To Printer.Properties_.Count)
r = 1
For Each Item In Printer.Properties_
c = c + 1
If Item.Name = "Name" Then NameIndex = c
Results(r, c) = Item.Name
Next
Exit For
Next

For Each Printer In Printers
r = r + 1
c = 0
For Each Item In Printer.Properties_
c = c + 1
Results(r, c) = Item.Value
Next
Next

Dim SheetsInNewWorkbook As Long
SheetsInNewWorkbook = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 2
With Workbooks.Add
With Worksheets(1)
.Range("A1").Resize(UBound(Results), UBound(Results, 2)).Value = Results
.Columns(NameIndex).Cut
.Columns(1).Insert Shift:=xlDown
.ListObjects.Add(xlSrcRange, .Range("A1").CurrentRegion, , xlYes).Unlist
.Columns.AutoFit
.Range("A1").CurrentRegion.Copy
End With
With Worksheets(2)
.Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
Application.CutCopyMode = False
.Columns.AutoFit
End With
End With
Application.SheetsInNewWorkbook = SheetsInNewWorkbook
End Sub

关于excel - 通过 VBA 设置默认打印机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58929416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com