在Excel VBA中select打印机

当试图在Excel中的特定打印机上打印时,当服务器更改其提示时,会显示一条错误消息。 当试图解决这个问题时,我使用了“在错误恢复下一个”function,但这只是丑陋的(并不是所有的时间)。

这是我目前的公式

Application.ScreenUpdating = False ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne01:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne02:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne03:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne04:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne05:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne06:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne07:" On Error Resume Next ActivePrinter = "\\w8vvmprint01\Moecombi04 op Ne08:" On Error Resume Next 

我能做些什么来解决这个问题?

 #If VBA7 Then Private Declare PtrSafe Function GetProfileString Lib "kernel32.dll" Alias "GetProfileStringA" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long #Else Private Declare Function GetProfileString Lib "kernel32.dll" Alias "GetProfileStringA" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long #End If 
 Public Function GetPrinterPort(ByVal PrinterName As String) As String Dim t As Long Do GetPrinterPort = String$(Len(GetPrinterPort) + 256, 0) t = GetProfileString("PrinterPorts", PrinterName, "", GetPrinterPort, Len(GetPrinterPort)) Loop Until t < Len(GetPrinterPort) - 1 If t <= 0 Then Err.Raise 5, , "Cannot get printer port for " & PrinterName GetPrinterPort = Split(Left$(GetPrinterPort, t), ",")(1) End Function 

用法:

 port = GetPrinterPort("\\w8vvmprint01\Moecombi04") 

然后使用port来构build完整的打印机名称。 您可能想要尊重本地化问题 。