How to Code Function in Excel

Learn multiple Excel methods to code function with step-by-step examples and practical applications.

excelformulaspreadsheettutorial
11 min read • Last updated: 7/2/2025

How to Code Function in Excel

Why This Task Matters in Excel

Every piece of data that flows through Excel ultimately consists of individual characters: letters, digits, punctuation marks, currency symbols, line breaks, and even invisible control characters. In day-to-day work you normally focus on the words or numbers those characters create, but there are many real-world scenarios where you need to drill down to the underlying character codes:

  • Data integration and cleansing – When you import files from different systems you frequently discover “mysterious characters” that break formulas or Power Query steps. Identifying the exact numeric code of the offending character lets you decide whether to strip it out, replace it, or convert it to something readable before further processing.

  • Reporting automation – In finance or legal reporting you might need to insert trademark, copyright, or custom bullet symbols that are not available on the keyboard. By knowing the numeric code, you can generate or validate those symbols programmatically instead of pasting them manually every month.

  • Cybersecurity and privacy – Masked data often replaces sensitive characters with asterisks or Unicode blocks. Auditors sometimes reverse-engineer files to confirm whether asterisks have really replaced the entire string or only part of it. Character codes give a deterministic way to verify the masking.

  • Barcoding and encoding – Manufacturing and logistics systems rely on specific ASCII or Unicode sequences to generate Code128, Code39, or QR barcodes. Confirming the numeric value of each character is mandatory to build valid strings that scanners can read.

  • Text analytics – NLP tools distinguish between the plain space (code 32) and non-breaking space (code 160). Excel is still the fastest way for many analysts to tag thousands of text rows and export a clean file for Python or R.

Excel’s built-in CODE function is the simplest tool for these jobs. Paired with its inverse, CHAR, plus helper functions like UNICODE and UNICHAR in modern Excel, you can inspect, validate, and generate any character that Windows or macOS supports. Without those skills you might waste hours hunting invisible issues, mis-encode data for back-end systems, or deliver reports peppered with replacement “▯” boxes. Mastering character codes plugs directly into other core skills—text parsing, data validation, and automation with dynamic arrays—and gives you a deeper understanding of how Excel stores text.

Best Excel Approach

The quickest and most robust way to reveal a character’s numeric representation is the CODE function. Its syntax could not be simpler: you pass a single-character text string, and Excel returns the code number used in your operating system’s current character set (Windows-1252 on most English Windows PCs, MacRoman or UTF-8 on recent Macs).

=CODE(text)
  • text – A required argument that must evaluate to exactly one character. If you supply more than one character, CODE ignores everything after the first character.

Why choose CODE?

  1. It is a native worksheet function—no VBA, no add-ins, no complex setup.
  2. It offers consistent results across all modern Excel versions, including Excel for the web.
  3. It works seamlessly inside dynamic array formulas, spilling results for thousands of cells with one entry.

When to consider alternatives:

  • If you need the Unicode code point of characters outside the basic ASCII range (for example emojis or most Asian scripts), use UNICODE instead.
  • If you need to reverse the process—convert a code back into a visible character—use CHAR or UNICHAR.
  • VBA’s Asc or AscW functions are viable in macros but are unnecessary in a normal worksheet model.
=UNICODE(text)     'modern alternative for full Unicode
=CHAR(number)      'inverse of CODE
=UNICHAR(number)   'inverse of UNICODE

Parameters and Inputs

Proper inputs make or break character code analysis:

  • Required argument – A single-character text value such as \"A\", \"ç\", or CHAR(10). The input may be typed directly in quotes, referenced from a cell, produced by another formula, or extracted with MID or LEFT.

  • Data type – Excel treats all text as Unicode strings internally, but CODE outputs a decimal integer between 0 and 255 on Windows and different ranges on macOS for historic compatibility.

  • Optional parameters – None. Simplicity is one of CODE’s strengths. If you need extra parameters (e.g., specifying a code page), you must move to Power Query or VBA.

  • Data preparation – Trim leading and trailing spaces first, because spaces are valid characters (code 32) and may mislead your investigation.

  • Validation – If the input is empty, CODE returns a #VALUE! error. If the input contains multiple characters, only the first character’s code is returned, which can mask underlying issues. Combine LEN(text)=1 to enforce single-character rules when necessary.

  • Edge cases – Control characters like line feed (code 10) or carriage return (code 13) are invisible but still occupy a position in the cell. Use CLEAN or SUBSTITUTE to remove them after detecting their code.

Step-by-Step Examples

Example 1: Basic Scenario

Imagine you receive a CSV export from a CRM system and notice several customer names with “weird spaces” that prevent VLOOKUP from matching. You suspect non-breaking spaces have replaced normal ones.
Sample data in [A2:A6]:

  • \"ACME[nbsp]Corporation\"
  • \"Blue[nbsp]Skies\"
  • \"Sunrise Ltd\"
    (The visible gap looks like a normal space, yet formulas fail.)

Step 1 – Isolate the first questionable character.
Enter in B2:

=MID(A2,SEARCH(" ",A2),1)

Step 2 – Reveal its code.

=CODE(B2)

Copy down to B6. You discover the result 160, not 32. Result 160 confirms a non-breaking space.
Step 3 – Replace the rogue character.

=SUBSTITUTE(A2,CHAR(160)," ")

Drag down and everything aligns.
Why it works: CODE tells you the numeric difference so you can replace the exact culprit instead of every possible space.
Troubleshooting tips: If SEARCH returns #VALUE!, there may be no spaces at all. Use LEN and TRIM for additional diagnostics.

Example 2: Real-World Application

A manufacturing company must create serial numbers that embed control characters to direct label printers. The printer interprets code 29 (Group Separator) as a “function character” dividing fields. Operators cannot type that from the keyboard.

Step-by-step:

  1. Design the base serial in column A:
  • Row1: \"ITEM12345\"
  • Row2: \"ITEM12346\"
  1. In column B add the function separator dynamically:
=CHAR(29)
  1. Build the final string in column C:
=A2 & CHAR(29) & "LOT" & TEXT(TODAY(),"YYMMDD")

Now C2 produces \"ITEM12345[GS]LOT240501\" where [GS] is the invisible control character.
4. Verify the control character exists by testing CODE:

=CODE(MID(C2,LEN(A2)+1,1))

The result 29 assures quality engineers the correct delimiter will reach the printer.
Integration: Feed column C into Power Query or export as a tab-delimited file without risk of manual keystroke errors.
Performance: Because CHAR and CODE are both lightweight, this solution scales to hundreds of thousands of labels without noticeable recalculation lag.

Example 3: Advanced Technique

Large multilingual datasets introduce Unicode beyond 255. Suppose an e-commerce marketplace processes product titles in Mandarin and emoji. You need to confirm whether all titles stored in the cloud database survive round trips through an older on-premises middleware that only supports characters up to code 65535 (Basic Multilingual Plane).

Dataset in [A2:A4]:

  • \"新品🎉速购\"
  • \"限量✨珍藏\"
  • \"超值🔥折扣\"

Advanced steps:

  1. Spill each character of a title into separate cells with the new TEXTSPLIT function:
=TEXTSPLIT(A2,,)
  1. In the next row, convert the spill to codes using UNICODE in one dynamic array:
=UNICODE(B2#)
  1. Wrap with MAX to detect any character above 65535:
=MAX(UNICODE(B2#))
  1. If the max exceeds 65535 flag an error:
=IF(MAX(UNICODE(B2#))>65535,"🚨 Out of Range","OK")

Professional tips:

  • Use LET to avoid recalculating UNICODE twice.
  • For very large datasets, push the transformation to Power Query where UNICODE is available through M functions, reducing worksheet volatility.
  • Add conditional formatting to highlight “Out of Range” rows in red for quick auditing.

Tips and Best Practices

  1. Always wrap suspect strings in CLEAN to strip codes 0–31 when you load data from legacy systems.
  2. Combine CODE with EXACT to test case sensitivity: EXACT works on visible text; CODE verifies hidden differences like “é” (233) vs “e” (101).
  3. Use CHAR(10) inside CONCAT or TEXTJOIN to insert line breaks when building emails or reports; validate them with CODE to prevent unintended 13/10 combos from macOS files.
  4. When documenting your work, annotate the meaning of each special code directly in adjacent columns, so future users won’t guess what 29 or 160 stands for.
  5. Create a small lookup table that lists critical characters and their codes. This makes troubleshooting faster and keeps your formulas cleaner.

Common Mistakes to Avoid

  1. Assuming CODE returns Unicode for all characters – On Windows it caps at 255; emojis will show as 63 (the question-mark box). Use UNICODE instead.
  2. Feeding multi-character strings – CODE reads only the first character. Use MID to isolate a specific position when analysing long strings.
  3. Ignoring different OS code pages – A file generated on macOS may yield different codes on Windows. Always re-test after platform changes.
  4. Deleting “blank” characters without checking – That invisible space may be a non-breaking space required in HTML. Verify with CODE before replacement.
  5. Forgetting to convert numeric codes to numbers – If you wrap CODE inside TEXT functions the result may become text, breaking numeric comparisons. Coerce with VALUE when needed.

Alternative Methods

MethodScopeProsConsTypical Use
CODE0-255 ASCIINative, fast, backward compatibleLimited rangeQuick checks in Western languages
UNICODEFull UnicodeModern, covers emojis & CJKNot supported in Excel 2010Multilingual datasets
VBA Asc/AscWASCII or UnicodeCan loop files, automateRequires macro securityLarge batch processing
Power Query Character.ToNumberUnicodeMemory efficientLearning curveETL pipelines
External tools (Notepad++, Python ord)UnlimitedScriptableOutside ExcelComplex cleansing workflows

When to switch: Use CODE for light checks, UNICODE for modern ranges, VBA for macro automation, Power Query for heavy ETL, external scripts for enterprise pipelines.

FAQ

When should I use this approach?

Use CODE whenever you suspect hidden or special characters in a dataset—cleaning CRM exports, verifying printer control codes, or debugging lookup failures. If the characters can be outside the standard 0-255 range, pivot to UNICODE.

Can this work across multiple sheets?

Yes. Reference the target cell on another sheet, for example:

=CODE(Sheet2!A5)

If you need to analyse entire columns across sheets, wrap CODE inside BYROW or map it with dynamic arrays that point to the external sheet’s range.

What are the limitations?

CODE on Windows cannot return codes above 255. It also ignores every character after the first in a supplied string. Finally, platform-specific code pages mean the same character may produce different numbers on Mac vs Windows.

How do I handle errors?

  • #VALUE! arises from empty strings—test with IFERROR or LEN=0.
  • Unexpected 63 means you passed a Unicode char without using UNICODE.
  • Phantom line breaks persist? Combine CLEAN, TRIM, and SUBSTITUTE based on the code numbers you discover.

Does this work in older Excel versions?

CODE has existed since Excel 2.0, so it works even in Excel 2003. UNICODE and UNICHAR require Excel 2013+ on Windows and Excel 2016+ on Mac. If you are constrained to older versions, lean on CODE (range 0-255) or VBA’s AscW.

What about performance with large datasets?

CODE is extremely light; 1,000,000 CODE calls recalculate in under a second on modern hardware. For 100,000-plus rows where you also manipulate text, cache results in helper columns and disable automatic calculation during data imports. Consider Power Query for complex transformations.

Conclusion

Mastering character codes may feel niche, yet it unlocks a powerful diagnostic lens on any text-based workflow in Excel. From swiftly locating non-breaking spaces to confidently embedding control characters for barcode printers, the CODE function and its Unicode relatives provide transparent, repeatable solutions that beat guesswork every time. Add this tool to your repertoire, pair it with TEXT functions and dynamic arrays, and you’ll troubleshoot mysterious data issues in minutes instead of hours. Next, experiment with UNICODE and UNICHAR on multilingual data to round out your character-level skillset and push your Excel proficiency to the next level.

We use tracking cookies to understand how you use the product and help us improve it. Please accept cookies to help us improve.