How to Automate Barcode Placement in Word with VBA

An example how to use the barcode generator in Word, how to resize and change position of the barcode with VBA.

See more barcode making examples in the related tutorials.

Making a barcode in Word with ActiveX and VBA

Requirements

How to run the code

1. In Microsoft Word, press Alt+F11 to open the VBA window;

2. Double-click the ThisDocument entry in the VBA project tree;

3. Paste the code into the editor;

4. Add a reference to the StrokeScribe ActiveX into your VBA project before running the code;

5. Move the caret in to the MakeBarcode() sub body and press F5 to run the code.

The code example

Sub MakeBarcode() Dim doc As Word.Document Set doc = Word.ActiveDocument ' The barcode will be inserted into the currently active document On Error Resume Next ' Deleting a previously created barcode object doc.Shapes("barcode").Delete On Error GoTo 0 With doc.PageSetup ' The page size, excluding margins TextWidth = .PageWidth - .RightMargin - .LeftMargin TextHeight = .PageHeight - .TopMargin - .BottomMargin End With Dim page As Range Set page = doc.GoTo(wdGoToPage, wdGoToAbsolute, 1) ' Inserting the barcode on the page 1 Dim shp As Shape ' Inserting the barcode object Set shp = doc.Shapes.AddOLEControl(ClassType:="STROKESCRIBE.StrokeScribeCtrl.1", Anchor:=page) shp.LockAspectRatio = msoFalse shp.Width = Word.CentimetersToPoints(3) ' The barcode dimensions are 3x2cm. shp.Height = Word.CentimetersToPoints(2) shp.Left = TextWidth / 2 - shp.Width / 2 ' Centering the barcode shp.Top = TextHeight / 2 - shp.Height / 2 shp.Name = "barcode" Dim barcode As StrokeScribe ' Accessing the barcode properties Set barcode = shp.OLEFormat.Object barcode.Alphabet = PDF417 barcode.Text = "123ABC" If barcode.Error Then MsgBox barcode.ErrorDescription End If End Sub

Related Tutorials