A maintenance team receives a new batch of laptops. A warehouse relocates spare parts. An office replaces chairs, monitors, and projectors. The spreadsheet already contains the asset IDs—but printing and attaching a scannable label to each item is still a manual, error-prone job.
This is where a small Excel VBA tool can be genuinely useful. It can read an asset code or inventory identifier from each row, create a QR code, place that image beside the record, and leave the worksheet ready for review or label printing.
The QR code is not the inventory system by itself. It is a fast bridge between a physical object and a digital record. When its contents are planned carefully, a phone or scanner can identify an item without someone having to retype a long code.
This guide builds a practical Windows Excel solution, explains the design decisions behind it, and highlights the limits that matter before the tool is used on real assets.
📦 Start with the problem the tool will solve
Inventory tracking usually fails at the handoff between the physical and digital worlds. A record may be accurate in Excel, but a technician standing in front of fifty similar cartons still needs a reliable way to identify the correct one.
A QR code can contain an asset ID, a stock-keeping unit (SKU), a web address to an internal record, or structured text. Your VBA tool should have one narrow responsibility: turn each approved value in a worksheet into a consistently sized QR image.
🔲 Understand what a QR code actually stores
A QR code is a two-dimensional barcode. Its black-and-white modules encode data along with error-correction information, allowing many scanners to read it even when part of the symbol is obscured or damaged.
It does not “know” what an asset is. If the code stores LT-2025-0048, a scanner returns that text. If it stores an internal URL, the scanning device may offer to open that URL. The meaning comes from your workflow, not from the image.
🎯 Choose the data to encode before writing VBA
The safest starting point is usually a stable, unique asset identifier. A short identifier produces a less dense code, which is generally easier to print and scan than a large block of descriptive text.
- Identifier only: useful when staff search for the returned code in a system.
- Internal record URL: useful when authorized mobile devices can open a web-based asset record.
- Structured text: useful for offline workflows, but should be kept concise.
Avoid encoding passwords, personal information, purchase values, or other sensitive fields. Anyone with a scanner can normally read the contents of a visible QR label.
🧭 Map the worksheet before automating it
A clear layout keeps VBA simple and makes errors visible. For this example, create a worksheet named Assets with headers in row 1: Asset ID in column A, Description in column B, Location in column C, QR Data in column D, and QR Code in column E.
Column D is intentional. It separates the value printed in the QR symbol from the identifying details used by people. You might put only an asset ID there, or use a formula that builds an approved record URL.
🧱 Use a table-like structure even without an Excel Table
The macro needs to know where the list ends. Reading upward from the last used cell in column A is a practical approach when every valid record has an Asset ID.
For more formal workbooks, converting the range into an Excel Table gives users structured rows, filters, and clearer expansion behavior. The code below uses a normal range so the essential VBA remains easy to follow, but the same ideas apply to a ListObject.
🛡️ Define a unique ID rule
A QR generator can create two identical images without warning if two rows contain the same input. Excel automation cannot decide whether that duplicate is intentional, so the business rule must come first.
Decide whether IDs are unique across all assets, unique only within a site, or assigned from another system. Then validate duplicates before labels are printed. A code that scans correctly can still point to the wrong asset if its underlying identifier is ambiguous.
🧪 Prepare a small test sheet first
Do not begin with a thousand live records. Add five hypothetical rows, including a normal ID, a blank QR Data cell, a long value, and two deliberately duplicated values.
This small test exposes layout problems early: images may overlap cells, row heights may be too small, or the generated values may not be what you expected. Testing with fake records also avoids sending real internal identifiers to a public service while you are still experimenting.
🔐 Consider where QR images will be generated
Excel VBA does not include a built-in QR-code encoder. A straightforward solution is to ask an external QR image service for a PNG file, download it, and insert it into the worksheet.
That convenience has a privacy implication: the encoded data is included in a web request. For public item numbers this may be acceptable; for confidential identifiers or internal URLs, ask your organization whether an external service is permitted. An approved internal generator or an offline QR library may be the better design.
🌐 Know the role of the web service endpoint
The example macro uses a QR image endpoint in this form: https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=.... The service responds with an image that Excel can save temporarily and insert.
This is a teaching-friendly integration, not a promise that any public endpoint will remain available, free, or suitable for your organization. Build the worksheet logic so the generator can be replaced later without redesigning the inventory process.
🧰 Enable the Developer tools and save correctly
In Excel, enable the Developer tab through Options if it is not visible. Choose Developer, Visual Basic, then Insert, Module to create a standard module for the macro.
Save the workbook as Excel Macro-Enabled Workbook (*.xlsm). A standard .xlsx file cannot retain VBA code. Keep an original copy of the inventory data before running any macro that inserts or deletes worksheet objects.
📝 Write formulas for QR data when useful
For an identifier-only design, copy the Asset ID into QR Data. For a URL-based design, a formula may build the destination consistently, such as ="https://assets.example.internal/item/"&A2.
Use a domain and route that your devices can actually reach. A QR code with a beautiful URL is not useful to warehouse staff if the mobile device lacks network access, authentication, or permission to view the destination.
🔤 URL-encode data instead of joining text blindly
Characters such as spaces, ampersands, slashes, and non-English characters can change the meaning of a URL query string. URL encoding converts the data into a transport-safe form before it is appended after data=.
This is especially relevant for descriptions and URLs. The code below encodes UTF-8 bytes rather than assuming asset data contains only letters and numbers.
💻 Add the VBA module code
Paste the following procedure and helper functions into the standard module. It uses late binding for the HTTP and stream objects, so you do not need to set a VBA reference manually for those components.
Option Explicit
Public Sub CreateAssetQRCodes()
Const SHEET_NAME As String = "Assets"
Const FIRST_DATA_ROW As Long = 2
Const DATA_COLUMN As Long = 4 'Column D
Const QR_COLUMN As Long = 5 'Column E
Const QR_SIZE As Long = 90 'Points on worksheet
Dim ws As Worksheet, lastRow As Long, r As Long
Dim qrData As String, tempFile As String
Dim shp As Shape, madeCount As Long, skippedCount As Long
Set ws = ThisWorkbook.Worksheets(SHEET_NAME)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Application.ScreenUpdating = False
Application.StatusBar = "Creating QR codes..."
For r = FIRST_DATA_ROW To lastRow
qrData = Trim$(CStr(ws.Cells(r, DATA_COLUMN).Value))
DeleteQRForRow ws, r
If Len(qrData) > 0 Then
tempFile = Environ$("TEMP") & "\QR_" & r & ".png"
DownloadQR qrData, tempFile
Set shp = ws.Shapes.AddPicture(tempFile, _
msoFalse, msoTrue, _
ws.Cells(r, QR_COLUMN).Left + 2, _
ws.Cells(r, QR_COLUMN).Top + 2, QR_SIZE, QR_SIZE)
shp.Name = "QR_Row_" & r
shp.Placement = xlMoveAndSize
ws.Rows(r).RowHeight = QR_SIZE + 4
ws.Columns(QR_COLUMN).ColumnWidth = 15
madeCount = madeCount + 1
Else
skippedCount = skippedCount + 1
End If
Next r
Application.StatusBar = False
Application.ScreenUpdating = True
MsgBox madeCount & " QR code(s) created. " & _
skippedCount & " row(s) skipped because QR Data was blank.", vbInformation
End Sub
Private Sub DownloadQR(ByVal qrData As String, ByVal filePath As String)
Dim http As Object, stream As Object, endpoint As String
endpoint = "https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=" _
& UrlEncodeUtf8(qrData)
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", endpoint, False
http.Send
If http.Status <> 200 Then
Err.Raise vbObjectError + 1000, "DownloadQR", _
"QR image request failed. HTTP status: " & http.Status
End If
Set stream = CreateObject("ADODB.Stream")
stream.Type = 1
stream.Open
stream.Write http.responseBody
stream.SaveToFile filePath, 2
stream.Close
End Sub
Private Sub DeleteQRForRow(ByVal ws As Worksheet, ByVal rowNumber As Long)
On Error Resume Next
ws.Shapes("QR_Row_" & rowNumber).Delete
On Error GoTo 0
End Sub
Private Function UrlEncodeUtf8(ByVal text As String) As String
Dim stream As Object, bytes() As Byte, i As Long, b As Long
Dim result As String
Set stream = CreateObject("ADODB.Stream")
stream.Type = 2
stream.Charset = "utf-8"
stream.Open
stream.WriteText text
stream.Position = 0
stream.Type = 1
stream.Position = 3 'Skip UTF-8 byte-order mark
bytes = stream.Read
stream.Close
For i = LBound(bytes) To UBound(bytes)
b = bytes(i)
If (b >= 48 And b <= 57) Or (b >= 65 And b <= 90) Or _
(b >= 97 And b <= 122) Or b = 45 Or b = 46 Or _
b = 95 Or b = 126 Then
result = result & Chr$(b)
Else
result = result & "%" & Right$("0" & Hex$(b), 2)
End If
Next i
UrlEncodeUtf8 = result
End Function
⚙️ See what the main procedure does
CreateAssetQRCodes finds the final populated row in column A, then loops through each record. It reads QR Data from column D, removes a previous QR image for that row, downloads a new image, and positions it in column E.
Naming each shape QR_Row_ plus its row number gives the macro a predictable way to replace images on later runs. Without this step, rerunning the tool would stack new images over old ones.
📥 Understand the download and temporary-file steps
DownloadQR sends a synchronous HTTP request, meaning VBA waits for the reply before continuing. It then writes the response bytes to a PNG file in the user’s temporary folder.
Shapes.AddPicture inserts that file into the sheet. The image is embedded because the macro passes msoTrue for the save-with-document argument. That means the workbook retains the inserted images even if the temporary PNG files are later removed.
📏 Size codes for real scanners, not just the screen
The macro requests a 180-by-180 pixel source image and displays it at 90 Excel points. The best physical size depends on printer resolution, label material, scanning distance, and the density of the encoded value.
Keep a clear border around the QR symbol. This blank margin, often called the quiet zone, helps scanners distinguish the code from nearby text, borders, and graphics. Avoid squeezing the image until its individual modules become blurred by printing.
🖨️ Build a label-ready print layout
The QR image column is only the data-production stage. For physical labels, create a separate Label sheet that references the asset ID, description, location, and QR image layout you need.
Set print area, margins, row heights, and page breaks deliberately. Print a single test page at the actual printer before generating a full run. A code that looks sharp on a monitor may become unreadable after scaling, toner spread, or a low-quality label print.
📱 Test scanning under working conditions
Use the type of phone or dedicated scanner that staff will actually use. Test labels on a desk and on the surfaces where they will live: curved equipment, cardboard cartons, reflective cases, or dusty shelves.
Confirm both parts of the workflow: the device reads the intended data, and the resulting record lookup or process works. A scan result can be technically accurate yet operationally unhelpful if it opens an inaccessible page or returns a code staff cannot search.
🔄 Decide when codes should be regenerated
Regenerate QR codes when the value in QR Data changes, when labels are redesigned, or when images become corrupted. There is no need to regenerate merely because a non-encoded description changes.
For a small workbook, rerunning the full macro is easy. For larger lists, an update macro could process only selected rows or compare an existing stored value with the current QR Data. Begin with the reliable full refresh before optimizing.
🧹 Prevent orphaned and misaligned images
Images are worksheet shapes, not cell values. If a user sorts only part of a range, deletes rows carelessly, or drags records without including the QR column, images can become disconnected from their intended assets.
The macro sets Placement = xlMoveAndSize, which makes the image move and resize with its cells in many normal operations. Still, train users to sort the entire data range or table, and rerun the generator after major restructuring.
🚧 Handle blank cells and bad requests gracefully
The supplied macro skips blank QR Data cells and reports the count at the end. That is better than creating meaningless labels, but it does not validate every business rule.
A production version can add checks for missing Asset IDs, duplicate values, excessive data length, or URLs that do not match an approved internal pattern. Error handling should also restore ScreenUpdating and the status bar if a network request fails midway through a run.
⚠️ Recognize the limits of row-based shape names
Using row numbers in shape names is ideal for a simple worksheet that is refreshed as a whole. It becomes less robust when people frequently insert rows, filter records, or move items between sheets.
A stronger design names the shape with a sanitized asset ID, or stores a mapping between the asset ID and shape name. That approach needs careful handling because shape names cannot contain every possible character and duplicate IDs must still be blocked.
🧩 Add validation before image generation
Validation turns a convenience macro into a more trustworthy operational tool. Before downloading anything, loop through the QR Data values and flag missing or duplicate entries.
A simple pattern is to use a late-bound Scripting.Dictionary: add each normalized value as a key, and report an error when the key already exists. Normalize deliberately—whether abc-1 and ABC-1 count as the same asset is a business decision.
🔒 Treat macro security and data security separately
Macro security concerns whether Excel should run the VBA code. Keep the workbook in a trusted organizational location where appropriate, use your organization’s approved macro practices, and do not encourage users to enable macros from unknown files.
Data security concerns what the QR code and web request reveal. Even a properly trusted macro may expose encoded values to an external endpoint. These are different risks and require different controls.
🏢 Plan for offline or restricted environments
The web-service approach requires internet access at generation time. It may fail behind a proxy, on a locked-down network, or during service interruptions. The already embedded QR images remain in the workbook, but creating new ones will not work.
Where availability or confidentiality is critical, investigate an internally hosted QR generation service or a vetted local component that produces QR images without transmitting data externally. The exact implementation depends on your IT environment and approved software.
📊 Compare common QR payload choices
| Payload choice | Best fit | Main trade-off |
|---|---|---|
| Short asset ID | Offline lookup and durable labels | Staff need access to a lookup process |
| Internal URL | Mobile-first asset management | Requires network access and authorization |
| SKU plus location text | Simple stock checks | May become outdated after relocation |
| Serialized structured text | Specialized scanner workflows | Needs a documented format and validation |
In most asset programs, a permanent ID is the least fragile payload. Locations, assigned users, and condition change over time; the identifier should remain the stable key that connects those changing facts.
🧑💼 Separate the label from the source of truth
Excel can be a useful lightweight register, but the printed QR label should not become the only record of ownership, status, or maintenance history. A label can be lost, copied, damaged, or attached to the wrong item.
Keep the authoritative record in a controlled worksheet, database, or asset-management system. The QR code should accelerate retrieval of that record, not replace normal checks such as serial-number verification when accuracy matters.
🪜 Improve the tool in sensible stages
Start with one reliable macro and a small test list. Once that works, practical enhancements include a button on the worksheet, a progress indicator for large runs, a log sheet for failures, and a separate label-printing template.
Later, you can add selected-row generation, duplicate reports, protected input columns, or an import process from another asset system. Each addition should solve a defined operational problem rather than making the workbook more complex simply because VBA can do it.
🧯 Troubleshoot the most common failures
- “Subscript out of range”: check that the worksheet is named exactly
Assets. - HTTP status error: check network access, endpoint availability, and any proxy restrictions.
- No image appears: confirm QR Data is in column D and that the row has not been hidden by an unexpected filter.
- Images overlap: check row heights, rerun the macro, and avoid manually moving generated shapes.
- QR code will not scan: print larger, reduce encoded text, preserve white space, and test at actual print scale.
If a macro stops with an error, do not repeatedly rerun it without inspecting the worksheet. First determine whether some rows already received images, then correct the cause and run a clean refresh.
✅ Use a repeatable operating checklist
- Back up the workbook or work from a controlled copy.
- Confirm every asset has a valid, unique identifier.
- Review QR Data for blanks, duplicates, and confidential content.
- Run the macro and read the completion message.
- Visually inspect several rows and scan a representative sample.
- Print one test page before producing the full label set.
- Record when labels were generated and which data version was used.
This checklist is short because most preventable problems occur before printing: unclear identifiers, untested data, unsuitable code size, and an unreviewed destination workflow.
🏁 Build for reliable identification, not just automatic images
The central principle is simple: automation should preserve the relationship between a physical asset, a stable identifier, and an authoritative record. VBA makes the repetitive image-creation step faster, but the surrounding data rules make it dependable.
A modest workbook with clear columns, safe payload choices, validated identifiers, and physical scan testing is more useful than an elaborate macro built on inconsistent inventory data. Treat QR generation as one part of a controlled tracking process.
A good Excel QR tool does not merely create squares to scan; it creates a dependable path from an item in someone’s hand to the correct record. Build that path carefully, test it where work happens, and improve it as your inventory process matures. ⚙️📦📱

