excelVBA實現(xiàn)產(chǎn)線流水號同時打印標(biāo)簽

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ù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,359評論 25 708
  • 1.1 VBA是什么 直到90年代早期,使應(yīng)用程序自動化還是充滿挑戰(zhàn)性的領(lǐng)域.對每個需要自動化的應(yīng)用程序,人們不得...
    浮浮塵塵閱讀 21,856評論 6 49
  • 一、誤刪資料恢復(fù) 一不小心刪錯了,還把回收站清空了,咋辦啊?只要三步,你就能找回你刪掉并清空回收站的東西。 步驟:...
    八爺君閱讀 1,563評論 2 7
  • 今天去銀行辦事,愛人說我有事你自己打車去吧,剛好小美睡了,我毫不猶豫爽快說好,學(xué)了金剛智慧,有力量了,對愛人的依賴...
    寸心潔白閱讀 181評論 0 1
  • p2p社科院排名 p2p社科院排名 p2p社科院排名
    蘇噶韭99695閱讀 435評論 0 0