Monday 13 February 2017

Generate barcode in Excel (VBA)

If you need to generate barcode in Excel spreadsheet and don't want to invest in specialized software or even a barcode printer, here is what you can do.

Specifications:
  • The following VBA code applies to Excel 2013 and above
  • You also need Word 2013 or above
  • The barcode generated here comply with the CODE39 specification. You can modify it in the codes below.
(1) Place the code below in a module.

Sub INSERT_BARCODE()
    Const BarcodeWidth As Integer = 156 '<-- Adjust to set width of barcode.
    Dim ws As Worksheet
    Dim WdApp As Object
    Dim BarcodeSource As Range

    Set ws = ActiveSheet
    Set BarcodeSource = ActiveCell.Value
    Set WdApp = CreateObject("Word.Application")
    With WdApp.Documents.Add
        .PageSetup.RightMargin = .PageSetup.PageWidth _
                                 - .PageSetup.LeftMargin _
                                 - BarcodeWidth
        .Fields.Add(Range:=.Range, _
                    Type:=-1, _
                    Text:="DISPLAYBARCODE " & CStr(sr.Value) & " CODE39 \d \t", _
                    PreserveFormatting:=False).Copy
    End With
    ws.PasteSpecial Format:="Picture (Enhanced Metafile)", _
                    Link:=False, _
                    DisplayAsIcon:=False
    WdApp.Quit SaveChanges:=False
    Set WdApp = Nothing
End Sub

(2) Select the cell which contains the number to be generated as barcode.
(3) Run the code above.

P/S: There are free internet based services which allow you to convert number to barcode for "free". But here is the drawback, you'll need internet connection, and you need to send them the numbers. Another way is to install Barcode Font, its easy to use but as far as i know, it's not free.

~Cheers

No comments:

Post a Comment