штрих код в excel code 128

Мой штрихкод. Code128

Однажды в процессе производственной деятельности у меня появилась необходимость генерации штрихкода по стандарту code128. Появилась в виду того, что имевшаяся в эксплуатации функция (хранимая процедура в базе Oracle) генерировала клёвый, полосатый штрихкод, который читался не во всех случаях. Разработчики в своё время оттестировали эту процедуру весьма некачественно, но перерабатывать уже не собирались т.к. проект был давно сдан, а потребности в считывании так и не появились.

Первая мысль — поиск готовых библиотек. Навскидку определили критерии — с pl/sql не связываемся, пусть это будет внешний сервис: возможно кусок на javascript для генерации прямо на страничке, либо обращение за картинкой к ближайшему серверу где имеется php. Беглый поиск в интернете показал что тема истоптана весьма плотно. Есть как наколенные поделки уровня лабораторки по программированию, так и мощные библиотеки для всех вариантов кодирования вплоть до qr-кодов. Варианты с JavaScript пришлось отбросить т.к. они во-первых практически все «обфусканы» (даже непонятно, то ли для сокращения объема, то ли стыдно исходники показать), во-вторых генерируют строку для отображения определенным шрифтом, наличие которого не всегда можно обеспечить на клиентском месте и требует дополнительных обработок для экранирования спецсимволов. Внимательное изучение библиотек и кусков кода на php тоже произвело тягостное впечатление — на первый взгляд всё вроде бы правильно: и классы написаны на все случаи жизни, комментарии в наличии, украшательства типа выбора цвета и рамочек, примеры подготовлены. Начнёшь вникать — хотят либо php самой распоследней версии (на боевых серверах не всегда это получается добыть), либо внутренняя логика не различима совсем, либо штрихкод на выходе получается длиннее ожидаемого. Вот последнее не дало покоя и подтолкнуло к собственной реализации.

Самое время пощупать теорию. Вернее мы с ней познакомились намного раньше, просто до последнего не хотелось ввязываться в дополнительное программирование. Исторические факты опустим, а вот очень хорошее техническое описание имеется на http://code128.narod.ru/ (в архиве это файл Descript.doc ) либо в Википедии. В принципе, это всё что нам потребуется для понимания и собственной реализации алгоритма (тут я немного лукавлю — из любой готовой библиотеки нужно выдрать таблицы толщин штрихов, чтобы не вбивать их вручную). Ну и напишем всё это безобразие на php, заодно посмотрим пару прикольных моментов, про которые все забывают или стесняются использовать.

Теория гласит, что code128 позволяет закодировать (сюрпрайз!) 128 символов, при этом нам доступно 3 алфавита, между которыми можно переключаться по ходу дела. Наибольший практический интерес представляют алфавит «B» для буквенно-цифровых символов и алфавит «С» который используется для кодирования цифр, но с некоторой оптимизацией — одним штриховым символом можно закодировать 2 исходных символа и получить более короткий штрихкод. Вот эта оптимизация пока не даётся ни одному php-разработчику — максимум что я видел это попытка в начале кодирования определить состав строки и при наличии только цифр переключаться на алфавит «С». В остальных библиотеках это банальная подстановка символов штрихкода по таблице.

штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

Сразу набросаем простейший класс который содержит сам текст, такие-же классы для рассмотрения вариантов по алфавиту B и С, длину последовательности. Делаем ему минимальный конструктор — на входе строка для кодирования, режим кодирования, ссылки на потомков. В начале конструктора добавляем проверки, чтобы не прорабатывать данную ветку дерева:

и сразу ловим конкретный косяк — куча «пустых» объектов. И это не смотря на то что мы явно отказались создаваться и вроде как железно возвращаем NULL! В общем сразу надо понять, что в php объект создаётся в любом случае. Полагаю что также и в остальных объектно-ориентированных языках. И все эти условия надо проверять перед созданием объекта. Следовательно правильный конструктор будет выглядеть примерно так:

Итак, худо-бедно мы нашли самый короткий путь (штрихкод). Надо его вывести для начала на экран. Делаем в два этапа: сначала от потомка возвращаемся к родителю. Итоговые символы, включая переключение между алфавитами, пушим (push) в массив. Да, в PHP есть такая функция, и она позволяет нам сделать из массива довольно удобный стэк.

Когда потребуется вывести строку — используем array_pop. Таким образом, мы по прежнему используем данный массив как стэк и легко выводим информацию в обратном порядке. Попутно готовим дополнительную обвязку для нашего штрихкода — старт/стоп/контрольная сумма.

Как этим пользоваться? В файл с классом в конец добавим пару строк:

попробовать можно сразу, вставив в html-страничку примерно вот такой тэг:

Источник

Создание штрих-кода в Excel

Excel – удивительное приложение, умеющее не только электронные таблицы, но и выполнять значительно большее количество действий. Например, генерировать штрих-коды. Для этого нужно воспользоваться специальным файлом, с помощью которого можно создать достаточное количество штрих кодов, и распечатать их.

Генератор штрих-кодов

Генератор штрих-кодов – маленький исполняемый модуль Excel, который позволяет создавать штрих-коды, основываясь на данных, указанных в таблице. Достаточно его скачать, установить специальный шрифт, и после этого можно приступать к работе. Но для начала нужно в целом понять, что такое штрих-коды и как они работают с научной точки зрения, так сказать.

Системы штрих-кодирования товаров, цифры штрих-кода

Для обычного человека нет принципиальной разницы между разными системами штрихкодирования товаров. Тем не менее, стандартной является та, которая имеет код EAN13. Первые три буквы в начале означают European Article Number, что переводится, как «Европейский Код Товара». Впрочем, эта система используется не только европейскими странами, но и везде. Структура штрих-кода этого типа следующая. В его состав входит тринадцать цифр, которые разделяются на несколько блоков:

штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

Таким образом, алгоритм штрих-кода очень четкий и нельзя его придумывать самостоятельно. Если попытаться воспользоваться сканером штрих-кодов, он выдаст ошибку, потому что алгоритм разработан исходя из имеющегося стандарта.

Некоторые штрих-коды не классифицируются описанным выше образом. Например, продукция может быть фасованной, и тогда штрих-код начинается с цифры 2. Также достаточно популярным форматом штрих-кодов, который используется для других целей, является QR-код. С его помощью можно зашифровать любую информацию.

Скачать генератор штрих-кодов

Итак, для генерации штрих-кодов в Excel необходимо скачать специальный файл (он полностью бесплатный) и открыть его. В скачанном архиве будет три файла:

После скачивания архива, его необходимо распаковать, а потом инсталлироввать шрифт, требуемый для выполнения поставленной нами задачи. Сам генератор штрихкодов находится по этой ссылке. https://www.tirika.ru/files/generator-shtrih-kodov.zip

Установка в Windows шрифта EAN13.ttf

Последовательность действий, необходимая для установки шрифта, несколько отличается. В последних версиях Windows отсутствует специальная кнопка для добавления шрифта, поэтому это нужно сделать другим методом.

Windows XP, более ранние версии ОС

Так, если у Вас операционная система Windows XP, нужно осуществить такие действия:

Windows 7, Windows Vista

Если у Вас Windows Vista и старше, в диалоговом окне выбора шрифтов нет кнопки «Добавить шрифт». Поэтому его нужно скопировать в перечень шрифтов вручную. Для этого надо открыть проводник и перетащить его туда так же, как и в какую угодно другую папку.

Запуск генератора штрих-кодов и его использование

Теперь наш шрифт установлен в Windows. После этого можно приступить к генерации штрих кодов с помощью одноименного файла в распакованном архиве. На этом этапе у пользователя может возникнуть такая проблема.

штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

По умолчанию для всех скачанных с интернета документов Excel автоматически выключает макросы, потому что они могут содержать вредоносный код. Дело в том, что программа Excel не только умеет создавать электронные таблицы, а поддерживает полноценное программирование. Язык, с помощью которого разрабатываются эти мини-приложения, называется VBA, что расшифровывается, как Visual Basic for Applications. Собственно, макросом называется программа, написанная на этом языке. С их помощью можно реализовать почти любую хотелку в электронных таблицах. Но некоторые пользователи разрабатывают плохие программные модули, поэтому разработчики Excel отключили их по умолчанию.

Файл, скачанный ранее, также является программой, написанной для Microsoft Excel. Здесь отсутствует вредоносный код, поэтому можно смело разрешать приложению открывать эти исполняемые модули. Если вы все же не очень доверяете макросам, скачанным с неизвестных источников, то можно просто удалить этот файл. Если их не включить, он не будет работать. Если вы доверяете файлу, то активируйте макросы, после чего нужно указать ряд несложных настроек. штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

Давайте разберем эти параметры более подробно:

После ввода параметров генератора штрихкодов, нам необходимо нажать на кнопку «Создать штрихкоды». После этого будет создан отдельный лист, в котором будут перечислены наши штрихкоды в первой колонке. Все шрифты будут нарисованы с использованием установленного ранее шрифта.

штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

Далее эта страница может быть распечатана, а потом ее можно и удалить. Если по тем или иным причинам штрих-коды оказываются ненужными, их можно убрать и ранее, поскольку всегда их можно сгенерировать заново. Зачем занимать лишнее место на диске?

По какому принципу работает этот генератор? После нажатия пользователем кнопки «Создать штрихкоды» создается новый лист, а одна из колонок заполняется сгенерированными штрих-кодами. Чтобы это сделать, сначала программа обрабатывает ту информацию, которая была указана пользователем на этапе настроек. Чтобы создать первую картинку, сначала берется префикс, который указал пользователь, после чего добавляет к нему первый номер, а потом добавляет определенное количество нулей. Сколько именно вставляется – определяется таким образом, чтобы получилась числовая последовательность в 12 символов. После этого рассчитывается последняя цифра, которые, как мы помним, генерируется по определенному алгоритму.

В результате, появляется 13-символьное число, записываемое в первую ячейку первого столбика листа, который был создан программой, после чего в ячейку B1 она добавляется, а для ячейки выставляется шрифт EAN13. После выполнения этих действий происходит создание второго штрихкода, которое выполняется по такому же алгоритму. Единственное исключение – номер увеличивается на единицу от предыдущего. Если сначала это было 1, то потом – 2, и так далее.

Алгоритм выполняется, пока не будет сгенерировано необходимое количество штрих-кодов. Затем перед пользователем появляется сгенерированный лист, и он может распечатать штрих-коды, которые получились.

Как самостоятельно сделать генератор штрих-кодов в Excel

А что если мы не хотим пользоваться чужими исполняемыми модулями, а хотим уметь делать такие коды самостоятельно? Для этого есть множество методов: создание собственной подпрограммы Excel, специализированный инструмент Active X и скачивание модулей, созданных другими пользователями.

Для начала можем установить специальный шрифт. Есть несколько шрифтов – не только тот, который мы скачивали ранее. Также по этому адресу можно найти специальную надстройку, предназначенную для достижения поставленной задачи. http://www.idautomation.com/font-encoders/word-excel-addin/.

Теперь нам нужно удостовериться, что был активирован Visual Basic. Ну и включить макрос, чтобы не изобретать велосипед, а создавать самостоятельно, но с использованием уже готовых инструментов. Для этого нужно выполнить следующую последовательность действий:

Дальше нам осталось только распечатать штрих-код и проверить его. Не забудьте перед этим убедиться, что применяются подходящие шрифты.

Процесс создания штрих-кода в Excel пошагово

Есть еще один метод создания штрих-кода в Excel – создание собственного макроса. Также можно добавить элемент Active X. В Excel 2007 версии и новее это делается следующим образом:

Если же нужно сделать так, чтобы он изменялся в зависимости от того, какие цифры будут введены пользователем, необходимо писать код.

Таким образом, эта процедура не такая сложная, как может показаться на первый взгляд. Уже все сделано за пользователя заботливыми программистами. Можно скачать отдельный файл, макрос, который можно использовать в собственной книге или же воспользоваться элементом Active X и создавать собственный макрос. Тем не менее, последний способ является довольно продвинутым, поэтому требует специальных навыков. А чтобы их развить, нужно изучить теорию, которая будет предметом отдельной статьи.

Источник

Easily generate Code 128 barcodes in Excel

This simple methodology can be employed to reliably generate Code 128 barcodes in Excel.

There are many methodologies published online for generating Code 128 barcodes in Excel. Unfortunately, most of them are complicated or don’t work in the later versions of Excel that most people use today.

A Code 128 barcode has six sections:

The check character is calculated from a weighted sum (modulo 103) of all the characters. Because of this, the generation of Code 128 barcodes is not as simple as typing the number sequence into a programme using a barcode font. Attempting to do this with Code 128 barcodes will fail.

Because I recently had reason to generate Code 128 barcodes, I felt it would be valuable to publish my methodology, which relies on the work of several other people. Follow these steps in order to create your own Code 128 barcode generator in Excel:

Step 1

Step 2

Ensure that you have the Developer module enabled in Excel. If not, follow these instructions.

Step 3

Create a new Microsoft Excel sheet. Create a table (making sure that you ‘format as table‘) with the following structure and headings:

BarcodeBarcode StringBarcode PresentationCheck
XXXX

Step 4

In Excel, go to the Developer ribbon and choose “Visual Basic”.

штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

Step 5

Right-click on “Modules” in the tree on the left and select “Insert Module”. Then paste the following code, which was written by Philip Treacy:

Step 6

Go back to your Excel sheet and insert the following formulae:

The formulae should copy down the entire columns. Save your sheet.

Step 7

Highlight Column C and change the font to “Code 128”. Now when you enter data into cell A2, a barcode should be displayed in cell C2 and so-on down the entire sheet.

If this doesn’t work, you may need to close and re-open Excel at this stage.

Some notes about usage

Unfortunately this script is not perfect and sometimes an a-circumflex (Â) character will be displayed in the middle of the barcode, particularly if copying numbers from other sources.

The formula in Column D is designed to display “Error” if this occurs so as to alert the operator. I added conditional formatting via the following rule: =$D:$D<>«» so that errors will be displayed:

штрих код в excel code 128. Смотреть фото штрих код в excel code 128. Смотреть картинку штрих код в excel code 128. Картинка про штрих код в excel code 128. Фото штрих код в excel code 128

Often the number can simply be copied and pasted back into the same cell, or re-typed. This doesn’t happen often.

A practical application

Whilst it’s nice to be able to generate Code 128 barcodes in Excel, this isn’t entirely useful on a practical level.

After generating the barcode strings (for example “ÍKLÈ3.323LΔ), these sequences can be copied and pasted into Word and the Code 128 font applied to them in order to generate a barcode. Unfortunately people need a human-readable number string beside a barcode, which means copying both the barcode string and the number sequence used to generate it. This is laborious and prone to error.

To get around this problem, I use a mail merge in Microsoft Word, combined with a sticker template to generate labels that contain both the barcode string (which is displayed in the Code 128 font) and the original number (which can be displayed in Arial, Times New Roman etc).

Mail merge can be tricky (a good subject for another post), but once mastered can make barcode generation very easy indeed. The other advantage with mail merge is that the barcode can be combined with other useful information on the label stickers in a manner which is efficient and unlikely to generate error.

Once the barcodes are generated in Word, they can easily be printed and affixed to whatever they’re designed to label.

Comments

69 responses to “Easily generate Code 128 barcodes in Excel”

Just wanted to say Thank You!

Thank you so much.
It is wonderful!

You just saved my life! Thanks man!

Does this work when trying to pass special characters like a horizontal tab. I’ve researched that a horizontal tab can be produced in code 128 using ^9 or possibly ^09. I would like a barcode for “String” + Horizontal Tab + “String”. Thanks in advance for your help.

Did you ever figure this out? I’m struggling too.

Any luck in finding how to generate Tab inside string?

Hi, I tried to follow this instruction but one error popped up when I entered the formula for C2. Excel said “the name that you entered is not valid. Reason for this can include: – the name does not begin with a letter or an underscore; – The name containes a space or other invalid characters; – the name conflicts with an Excel built – in name or the name of another object in the workbook.

Also, the Barcode String content looks weird with some characters being replaced by “?”.

Works great, wonderful work. I made sure to cite this source. Thank you.

Great website!
This function works very well with almost everything that I tested.
But it´s not generating a readable bar code 128 for some sequences like this one:
35160756642960000452590000879700000291361960

Can you try it?
Tks

Did not work. I followed the directions and generated a barcode but it would not scan. Thanks for the help anyway.

Your printed bar code may have been too small or alternatively the code was too close to the edge of the label. There are minimum clearance zones and font sizes that are required for the bar codes to work. I have also encountered this when it’s been printed too small.

Agreed. Seemed great but QR reader would not read the barcode generated

Great work here Philip! Thank you for the help. I am having trouble. There is a large space in the middle of my barcode when using the sequential values FP10001, FP10002, FP10003, etc. These are employee numbers so I have some control over them. So, I tried 10001FP, 10002FP, 10003FP, etc. and the problem is not as bad but many of the barcodes have a large blank in them.

I am feeling simple after reading everyones positive results.
I have Excel 2016.
I tried to do the steps as indicated.
In fields b2, c2, d2 I copied the formulas as directed and tje formula’s is now what is now displayed in b2, c2, d2. I did change the font for column C and it is displaying the formula as a barcode.

No matter what number I put in b2 the barcode in c2 seems to represent the formula (=[@[Barcode String]]) as a bar code.
Can someone help me with what I have missed. Thanks.

Following is an example of what I see in excel
Barcode Barcode String Barcode Presentation Check
12345 =Code128([@Barcode]) =[@[Barcode String]] =IF(ISNUMBER(SEARCH(“”,[@[Barcode Presentation]],1)),”Error!”,””)

It sounds like your cells may be formatted as text. Ensure that your cells are formatted as a number then try re-entering the formulae again. It should then work.

I had the same issue with the formulas looking as you typed here. The fix for me was adding a space after the “=” for each formula in B2, C2 and D2.
Hope that helps anyone trying to make this work!
Thanks Adam for the tutorial and Philip for the code.

I try this code in vb6 & barcode printing properly

but not scanning by barcode scanner.

Wow…works like a charm!!

no need to use it only on tables. just use like a normal formula in Excel.

Change font to Code 128.

My one did not work intially as I used a code 128 font from someone elses website. Just use the font as ginve by the developer in links above.

I am kind of stuck. I tried to install the font Code 128. And tried to insert the entire code in to the Visual basic by inserting the module. Without formatting as table, tried to add a ABC123 in A2 and in c2 I tried giving =Code128([@Barcode]) and also =Code128(A2)

But both returns error. I changed the formated the A2 as Number still no change. Can anyone plese elp me with this

i am using excel 2017, would it be okay?

Thanks for the tip.
I managed to build a sheet using this and combining it with mailmerge in word, for a laboratory application.
How about publishing the your example Word mailmerge doc as well?

One thing to check is that the paragraph character at the end of a line is not included. It’s best to change the font to any characters adjacent to the barcode mailmerge field to a normal text font. Otherwise, confounding characters will appear after the barcode in Word.

Yes, you are correct. I have noticed the same think. I have been contemplating writing about the Word part of this process but I’ve not yet found the time.

Thanks for this article, it was very useful for me. But I have problem: for example the “FA0175 12” Barcode value appears as “ĚFA-0175 12wΔ in the Barcode String cell. Or “3000-ARIA-60” get “Í> Č-ARIA-60[Δ. The Ě or Č or similar special characters appear in all my Barcode always.

Could you help to find the solution for this error?

Hi Adam,
thanks for publishing and sharing this approach.
Followed and works great.
Hope someone can throw some light to my problem.
if the the input is a special character like “-“, the
VB throws out as “-” (no coding )
but the Code128 interprets as “/”.

Any suggestion? Many thanks.

Receiving an error
The Syntax of this name isn’t correct.
Verify that the name:
-Starts with a letter or underscore
-Doesn’t include a space or character that isn’t allowed
-Doesn’t conflict with an existing name in the workbook

I would like to barcode a series of sku’s similar to this one: 1-73Ghz_E6510_QC

Barcode Barcode String Barcode Presentation Check
1-73Ghz_E6510_QC =Code128([@Barcode]) =[@[Barcode String]] =IF(ISNUMBER(SEARCH(“”,[@[Barcode Presentation]],1)),”Error!”,””)

The worksheet name is unrelated to anything in the formulas

Incredible solution… simple, perfect.

Having trouble getting bar codes to scan. Everything looks good in the spreadsheet. When I print various sized code 128 fonts it won’t scan. I’ve used various apps to capture the barcode. Nothing. Any other suggestions for a code that seems valid but just won’t scan? Thanks!

having the same issue…. barcode is generated, but none of my 2 scanners is able to read it….

My guess is that you may not have enough whitespace (border) around each code. Try spacing things out a bit and see how you go.

Hey just want to say thank you for the steps, now I wish I was proficient in excel to actually get this right, I have played but seems my knowledge of excel and the functions are not what I thought they were

thanks again anyway will try get someone to do this for me

Can I input carriage return in Code for Microsoft Access? And How?

Using Office 2016 and was getting “The syntax of this name isn’t correct” error. Used AHSANUL HAQ’s trick and was able to get it to work.

By simply putting =Code128(Cell Reference). Worked like a charm. Thank you all for the help and this amazingly simple approach.

Just to say thank you very much!
Very simple and understandable explanation.
It works perfectly!

THANK YOU!
Very helpful.

After I copy and past Module 2 and go back to the sheet to input the formulas, I get an error, “Ambiguous name detected: Code128” and the sheet does not work. Any suggestions?

Disregard, figured it out. I had another module installed that was conflicting with this one. When I removed it and only had the above code in place it works.

It is a fantastic work, helped me to. Thank you.

THANK YOU! This worked exactly as it was written and worked the way I needed to.

I have Excel 2016 and just got a new computer for work (the permissions scheme is different as our company changed ownership). I was running this code great on my old computer but for some reason it’s not working correctly on current machine.
First, per of I had to change the formula in colum B from: “=Code128([@Barcode])” to “=Code128(A2)” & the code in column C from: “=[@[Barcode String]]” to: “=B2” to avoid getting a formula syntax error that Excel would not let me over-ride.

But now the barcode in column C is not generating the proper string. I think it’s the leading character “Ì”. Sure enough, when I put this character in it is not generating the correct barcode for that individual character in the font (other characters seem fine though). I’ve reinstalled the font 3 times so I’m not sure why it would be mapping the incorrect barcode-“font” character. Of course, this manifests as being un-scannable by my scanners.

Any idea why it would be doing this? Is my change in syntax above to blame? Is there something wrong with my permissions/macros that would keep me from being able to run this VBA code?

Actually, it does appear to have been my font: must have been corrupted causing the incorrect mapping.

It appears my changes to the code do not affect the operation of this tool.

Excellent job! Thank you!

If you’re a VB noob like me, make sure you don’t have a name conflict. Don’t name the module Code128 since the sub procedure is already named Code128. You will end up with a #NAME? error as it is looking at the module first before the procedures within it.

This is really great. Having a strange problem, though – the values I’m encoding are a mix of uppercase letters and numbers, sometimes with a dash. My sample set worked great. In my “real data”, though, the barcode is ending up encoding the text as lower-case, which results in my item not being found after scanned.

Ex: sample data: “DF002-D1” encodes correctly, scan finds the associated item. In the “real data”, this value ends up encoding as ‘df002-d1’ resulting a not found error after scan.

I have a development background, and work with Excel a lot. This really saved me a lot of time and was very educational, but I cannot figure out why this value is ending up with lowercase is happening.

Any hints or tips or path to go down would be greatly appreciated.

Worked like a charm

Hi there, after struggling for a while I came up with this formula to generate the string. Perhaps is helpfull to someone.

Just paste the forumula in cell B1 (and asing a bar code true type font to it). Then write in cell A1 what you need to code.

Markos it works almost perfectly. Thanks a lot!

I had only one problem.
I am working with character combinations and in 90% of the cases it works correctly.

For example these are ok:

T00B0B4
T00B04F
T00AF4E
T00AF5D

T00B05C
T00B0C7
T00AF5B
T00B054

Here the function puts some special characters and those are not compatible with the font type.

Do you have any suggestions? Anybody?

If you are still looking for the answer to this, I have just come across this site looking to do the same mself and have managed to tweak Marcos’ code slightly to hopefully fix the issue:

This will hopefully resolve your issues with the check digit on certain codes. Also as per the comment by PERRY HOOGE, I think you may need a slightly different font download as the one in the link seems to be slightly corrupt. I used libre_barcode_128 and it worked a treat.

It’s works! Thanks you!

Thanks for helping me out with this. This was an efficient solution and I appreciate your coding expertise.

I really appreciate you sharing this work; it really saved me a lot of time!

This was incredibly helpful! Works like a charm! Careful, the web has a Code128 font that is corrupted. Found another copy that worked.

I do have a question though. Has anyone ever tried to get this working in MS Access? I’m not a great VBA coder so if anyone has this working in MS Access, please let the world know.

It works great – but it is important to use a correct code128 font – first I tried it with another one I had found – that didn’t scan. Combined with the LoMag Barcode scanner on my Android phone – it’s really great. The scannings are automatically saved in a file and the file can be uploaded to your cloud-service. Like another user I couldn’t make the original formulas work – but I just refererred to the cell names A2, B2, C2 etc. instead – just using the Code128 function to generate the string of (weird) characters. Thanks!

It work really well, but I have one issue: How can I encode a CR character?

Thank you very much. It’s very useful.

Does this work on MS Access? Would love the same guide but for MS access 🙂

Thank you for posting this code. It worked really good. Has anyone found a solution for the  error everything you had two zeros together? For example MC40100X144. Tried typing them instead of pasting, cell changed to =Code128(A2) etc but anything with a 00 somewhere in the middle generates that error.

Thank you in advance.

Everything worked great except the barcodes won’t scan. Tried different sizes, made sure there was a enough white space. Still won’t scan. Any one have any ideas?

Thank you for your work!
Unfortunately, the barcode is unreadable to me. First, I had to understand the difference between a generated barcode and a readable barcode. I found that the start and stop characters are different, my barcode uses code B instead of code A. Something about the check character is also different for something. On Wikipedia, I found the right characters as well as the calculation method.
After that I fixed the VBA code which now only uses Code B.
The next is to see if it helps anyone else.

Option Explicit
Public Function Code128(SourceString As String)

‘Written by Philip Treacy, Feb 2014
‘http://www.myonlinetraininghub.com/create-barcodes-with-excel-vba
‘This code is not guaranteed to be error free. No warranty is implied or expressed. Use at your own risk and carry out your own testing
‘This function is governed by the GNU Lesser General Public License (GNU LGPL) Ver 3
‘Input Parameters : A string
‘Return : 1. An encoded string which produces a bar code when dispayed using the CODE128.TTF font
‘ 2. An empty string if the input parameter contains invalid characters

Dim Counter As Integer
Dim CheckSum As Long
Dim mini As Integer
Dim dummy As Integer
Dim UseTableB As Boolean
Dim Code128_Barcode As String

If Len(SourceString) > 0 Then
‘Check for valid characters
For Counter = 1 To Len(SourceString)
Select Case Asc(Mid(SourceString, Counter, 1))
Case 32 To 126, 203
Case Else
MsgBox “Invalid character in barcode string.” & vbCrLf & vbCrLf & “Please only use standard ASCII characters”, vbCritical
Code128 = “”
Exit Function
End Select
Next

‘Create CODE_128B barcode
For Counter = 1 To Len(SourceString)
dummy% = Asc(Mid(SourceString, Counter, 1))
dummy% = IIf(dummy% http://generator.onbarcode.com/linear.aspx?TYPE=8&DATA=1234567&UOM=0&X=1&Y=60&LEFT-MARGIN=0&RIGHT-MARGIN=0&TOP-MARGIN=0&BOTTOM-MARGIN=0&RESOLUTION=72&ROTATE=0&BARCODE-WIDTH=0&BARCODE-HEIGHT=0&SHOW-TEXT=true&TEXT-FONT=Arial%7c9%7cRegular&TextMargin=6&FORMAT=gif&PROCESS-TILDE=false

paste it in cell A2 and change it to an image formula with the reference to A1 (after the text: DATA)

Write your text or number or combination in A1.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *