Skip to content

Using ZXing.Net with VBA (COM Interop)

Michael Jahn edited this page Sep 10, 2018 · 4 revisions

Since version 0.16.0 ZXing.Net contains a special assembly which can easily used from VBA via COM Interop. The assembly is a wrapper arround the core functionality of ZXing.Net. It makes the API easier usable.

First download the zip archive with the binaries of ZXing.Net (version 0.16.0 or higher). Extract the subdirectory "interop" from the archive. There is a command script "register.cmd" which adds the information from the zxing.interop.dll to the windows registry. The script uses the command regasm.exe.

All assemblies (dll) from the directory "interop" have to be in the search path because Access, Excel and others have to find it. The easiest way is to place the zxing.dll, zxing.interop.dll and register.cmd in the Windows directory (C:\Windows) and execute the script from there.

Now create a new module in your VBA project and add a reference to the ZXing.Net component.

Here are some code snippets for the most common tasks which can be uses in a VBA module:

Function Decode_QR_Code_From_File()
   Dim reader As IBarcodeReader
   Dim res As Result

   Set reader = New BarcodeReader

   reader.options.PossibleFormats.Add BarcodeFormat_QR_CODE

   Set res = reader.DecodeImageFile("D:\Barcodes\QrCodes\www.png")

End Function
Function Decode_QR_Code_From_Byte_Array()
   Dim reader As IBarcodeReader
   Dim rawRGB(1000) As Byte
   Dim res As Result

   Set reader = New BarcodeReader

   reader.options.PossibleFormats.Add BarcodeFormat_QR_CODE

   Rem TODO: load bitmap data to byte array rawRGB
   Set res = reader.DecodeImageBytes(rawRGB, 10, 10, BitmapFormat.BitmapFormat_Gray8)

End Function
Function Encode_To_QR_Code_To_File()
   Dim writer As IBarcodeWriter
   Dim qrCodeOptions As QrCodeEncodingOptions
   Dim pixelDataResult As PixelData

   Set qrCodeOptions = New QrCodeEncodingOptions
   Set writer = New BarcodeWriter
   writer.Format = BarcodeFormat_QR_CODE
   Set writer.options = qrCodeOptions
   qrCodeOptions.Height = 100
   qrCodeOptions.Width = 100
   qrCodeOptions.CharacterSet = "UTF-8"
   qrCodeOptions.Margin = 10
   qrCodeOptions.ErrorCorrection = ErrorCorrectionLevel_H

   writer.WriteToFile "Test", "D:\interop_qrcode.png", ImageFileFormat_Png

   Rem Or:

   Set pixelDataResult = writer.Write("Test")

End Function
Function Decode_QR_Code_From_File_CreateObject()
   Dim reader As IBarcodeReader
   Dim res As Result

   Set reader = CreateObject("ZXing.Interop.Decoding.BarcodeReader")

   reader.options.PossibleFormats.Add BarcodeFormat_QR_CODE

   Set res = reader.DecodeImageFile("D:\Barcodes\QrCodes\www.png")

End Function