image.png
一個簡單的界面
VBA代碼如下
Option Explicit
'保存所有的打印機
Dim arr() As String
Private Sub CommandButton1_Click()
If TextBox1 = "" Or TextBox2 = "" Then
MsgBox "流水號不能為空"
Exit Sub
End If
'記錄條碼內(nèi)容
With Sheets("listnumber")
Dim fng As Range
Set fng = .Range("b:b").Find(TextBox1.Text, , , xlWhole)
If Not fng Is Nothing Then
MsgBox "該流水號已經(jīng)存在"
Exit Sub
End If
'----------------------------------------
Dim rng As Range
Set rng = .Cells(Rows.Count, 1).End(xlUp)
rng.Offset(1, 0) = rng.Value + 1
rng.Offset(1, 1) = TextBox1.Text
rng.Offset(1, 2) = TextBox2.Text
End With
'調(diào)用打印過程
Call print_label(TextBox1.Text)
'條碼的內(nèi)容
TextBox1.Text = ""
TextBox1.SetFocus
End Sub
Private Sub UserForm_Activate()
TextBox2.Value = Format(Date, "yyyy-mm-dd")
'讀取所有的打印機
Call allprinter
End Sub
'定義print過程
Sub print_label(rng As String)
On Error Resume Next
Dim i%
Dim file_path
Dim btapp As BarTender.Application
Dim btformat As BarTender.Format
Dim ws As Object
Set ws = CreateObject("wscript.network")
Set btapp = CreateObject("bartender.application")
btapp.Visible = False
'-------------------------------------循環(huán)打印label
If UBound(arr) = LBound(arr) Then
MsgBox "您暫未安裝打印機"
Exit Sub
End If
For i = LBound(arr) To UBound(arr)
file_path = ThisWorkbook.Path & "\label\label" & i & ".btw"
'設(shè)置打印條碼
Set btformat = btapp.Formats.Open(file_path)
'將流水號設(shè)置到條碼上
btformat.SetNamedSubStringValue "ewm", rng
'設(shè)置打印格式
btformat.PrintSetup.IdenticalCopiesOfLabel = 1
'設(shè)置默認(rèn)的打印機
ws.SetDefaultPrinter (arr(i))
'打印文件
btformat.PrintOut
'關(guān)閉文件
btformat.Close btDoNotSaveChanges
Next
'關(guān)閉程序
btapp.Quit
End Sub
'取得所有的打印機保存在當(dāng)前的數(shù)組中
Sub allprinter()
Dim i&, ws As Object, st$, ptn$, n&
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) '打印機名稱
arr((i - 1) / 2 + 1) = ptn
Next
End Sub
注意事項:①listnumber表格需要自己建立,該表格的目的是為了保存刷入的流水號,防止重復(fù)。