Ravindra BagaleCourses & study guides मराठी Track your progress

5. Data Cleaning A–Z

Excel

5.9 Merging Columns

1. Make one useful label while keeping the original fields

Imagine a campus food festival with a spreadsheet inspired by the way people browse shops on Swiggy. Your volunteer team records the platform label, area, city and store code in separate columns. A printed pickup sheet needs a single short line such as FreshGo – Baner, Pune. The totals workbook still needs to filter by City and look up an exact Store code. Generate the line as an additional field and keep the original parts. These are fictional shops, figures and source rules for the exercise.

Joining pieces of text is called concatenation. It can produce a sentence or a compact label, yet it does not change the original fields or type needed by another calculation. Excel also uses the word merge for other operations. A worksheet's Merge Cells command changes the grid, a Power Query Merge joins two tables by matching fields, and Append stacks compatible rows. Choose the operation based on the result you need.

Keep a display label separate from identity. A nice label can repeat, be renamed or omit optional details. A reliable key follows the record's definition and needs its own checks.

Three source fields, platform FreshGo, area Baner and city Pune, compose a readable label while the separate code 0007 stays available for a lookup.
Keep the fields that support filtering and identification. Add a separate field for the printed line.

Decide which action matches your goal

  • Combine values in one row. A formula can join the fields from the same source record in a new cell. Use this for labels or text messages.
  • Change worksheet layout. Merge & Center creates one larger-looking cell area. In a normal left-to-right sheet, Excel retains the top-left content and deletes other values in the merged selection. When using a right-to-left sheet Excel's documented retained corner differs. Neither case generates a combined string. Do not merge populated data cells to build a label.
  • Bring facts from related tables. Join orders to a store reference table by a verified ID. Power Query Merge can match on one or several columns and lets you choose which records remain in the output. Verify that the reference contains one suitable match where you expect one.
  • Stack compatible records. Append sources covering different periods or shops to make a longer table. Verify matching column definitions and types. Appending a second month's rows does not match each sale to a store or combine values into one cell.

Pick punctuation based on the expected fields

The ampersand operator joins values in order. A literal separator in quotes adds exact visible punctuation. =D2&" – "&B2&", "&C2 works for a row that definitely has a platform, area and city. A truly empty Area still leaves the separator and comma that the formula requested. When area is optional, use a different formula that includes only suitable entries. Decide whether everyone without an area can keep a usable label and what status the report should show.

CONCAT accepts pieces or ranges and does not supply separator or ignore-empty arguments. Include separators with the other arguments if you need them. TEXTJOIN is useful when several parts need the same delimiter. Give the delimiter first, choose whether genuinely empty input cells in the range should be skipped, then supply the cells. Check the behavior of any formula result that appears empty and any space-only input in your workbook. A space-only value is still text. The first practice table uses actual blanks to keep the distinction easy to see.

2. Lab. Create a pickup label while preserving source identity

Goal. Create five approved display labels from seven source records. Keep their Store codes and location fields visible. Use a new Raw Labels sheet with the five leftmost columns in A1:E8. Preformat Store code as Text and leave the indicated cells truly blank. Copy the sheet to Work Labels. The practice contract requires City and Platform for a printed label. Area is optional. The city values are supplied as approved display text for this fictional report.

Fictional pickup points with expected labels
SourceAreaCityPlatformStore codeExpected label
M01BanerPuneFreshGo0007FreshGo – Baner, Pune
M02Tarabai ParkKolhapurMarketRush0042MarketRush – Tarabai Park, Kolhapur
M03Nirala BazarSambhaji NagarFreshGo0130FreshGo – Nirala Bazar, Sambhaji Nagar
M04PuneFreshGo0235FreshGo – Pune
M05KothrudFreshGo0550
M06DharampethNagpur0091
M07BanerPuneFreshGo0391FreshGo – Baner, Pune

Join the right parts in the right order

  1. Preserve typed columns

    Keep the work copy's Area, City, Platform and Store code. Verify that E2 contains the string 0007 and gives TRUE for ISTEXT. The print label may never show that code, but the source identifier must stay available.

  2. Test a punctuation-only join

    On a spare cell, try the simple ampersand formula on M01. It writes FreshGo – Baner, Pune exactly. For M04 the fixed punctuation would leave an extra comma. The formula cannot decide which fields are required. Add that rule explicitly.

  3. Join optional location parts

    Put Location text in F1. In F2 enter the TEXTJOIN helper below and fill down. The comma and space go between Area and City when both are present. M04 yields just Pune because the Area cell is actually blank.

  4. Check required fields before printing

    Use G1 Status and H1 Printed label. Enter G2:H2 and fill down. Two rows stay on hold, one for city and one for platform. Four labels use a stated area and one lacks an area but can still print. The labels themselves are text.

  5. Check two equal labels by identifier

    M01 and M07 print the same line but have different Store codes. Verify their exact codes before attempting any lookup. A duplicate label is legitimate here. Count five ready records and four distinct printed labels, and check that each raw record appears exactly once in the work copy.

F2 =TEXTJOIN(", ",TRUE,B2:C2)
G2 =IF(C2="","Review city",IF(D2="","Review platform",IF(B2="","Ready with city only","Ready with area")))
H2 =IF(OR(G2="Ready with city only",G2="Ready with area"),D2&" – "&F2,"")

Run a version with plain ampersands

On a copy of the practice sheet, replace the F helper with the formula below and compare its result in all seven rows. It handles two fields with optional blanks by adding punctuation only if both fields have content. For a short string this can be easier to read. In an exercise that joins a large range, TEXTJOIN may save a much longer set of checks. Microsoft lists TEXTJOIN for current supported versions including Microsoft 365 and Excel 2019 and newer; consult the function's version list for your platform.

F2 =IF(B2="",C2,IF(C2="",B2,B2&", "&C2))

Check that an incomplete row may still have a candidate in F. For M05 it is Kothrud, although the City required for publication is missing. H stays blank-looking and G names the reason. The candidate is useful for review. Replacing a trainable choice with IFERROR and a blank in every column would hide whether the missing input or the joining formula needs attention.

3. Lab. Compare a store-day group with an actual order key

Suppose a colleague suggests Store code plus Date as the unique key for each festival order. Two orders can happen in the same store on the same day. The proposed expression is useful for grouping daily receipts, while being insufficient for order identification. Before joining fields, say what one row represents. The exercise expects one source record per order. In a real order-line export, a verified line identifier could also be necessary.

Two orders for code 0007 on December 20 share the store-day group but have different order IDs, so separate order keys can preserve each record.
Use the same store-day key to group the orders. An order identifier distinguishes the individual orders within it.

Goal. Verify two valid orders can share a daily group, and hold both rows that share an intended order key until reviewed. Enter the first five columns in A1:E8 of a new Raw Orders sheet. Format the Store code column as Text. Put actual Excel dates in C, using DATE to enter them without relying on regional parsing. Leave B6 blank. Put numeric rupee amounts in E. Copy the sheet. This partner's stated order IDs in the accepted data cannot include the pipe delimiter.

Fictional December order records with expected review status
SourceStore codeOrder dateOrder IDAmount (INR)Expected status
T0100072026-12-20O1001320.50Ready
T0200072026-12-20O1002125Ready
T0300422026-12-20O1003260Review duplicate order key
T0400072026-12-21O100475Ready
T052026-12-20O100590Review store or day
T0600422026-12-20O1003260Review duplicate order key
T0700422026-12-20O|100550Review order ID
  1. Use one typed column per source field. Confirm dates are approved calendar values for December 2026. The store code is explicitly a four-digit string. DATE supplies each day, and you can choose your preferred date format while retaining the serial value. Confirm that E contains numeric rupees rather than text labels.
  2. Build a grouping key. Put Store-day group in F1 and fill F2 down. Use a text conversion for the approved date so the key has one stable Year-Month-Day order with no internal separator. For T01 you expect 0007|20261220. If you join the raw numeric date without TEXT you may see the date serial in the combined result, not the printed calendar date.
  3. Build an order candidate key. Put Order key in G1. Only a valid store-day value and allowed Order ID create the candidate. Inspect T07 and verify that its extra pipe is rejected. Comparing G2 and G3 shows that the two orders can share F while maintaining different order keys.
  4. Count exactly at each level. Put Store-day occurrences in H1 and Order occurrences in I1. Apply the two exact-count helpers below. The first two rows show two occurrences of their shared daily group and one for each order. T03 and T06 contain the same order key twice. A hold on both is appropriate until the event owner establishes the correct record or grain.
  5. Publish only the verified subset. Put Status and Approved amount in J1:K1. Fill down. Three Ready rows sum to 520.50, of which 445.50 belongs to store 0007 on 20 December. Four held rows hold known raw amounts totaling 660. The source total 1180.50 reconciles to both parts. This does not assume the suspected replay is effective revenue.
F2 =IFERROR(IF(AND(ISTEXT(B2),LEN(B2)=4,EXACT(B2,TEXT(--B2,"0000")),ISNUMBER(C2),C2=INT(C2),C2>=DATE(2026,12,1),C2<DATE(2027,1,1)),B2&"|"&TEXT(C2,"yyyymmdd"),""),"")
G2 =IF(OR(F2="",NOT(ISTEXT(D2)),D2="",ISNUMBER(FIND("|",D2))),"",F2&"|"&D2)
H2 =IF(F2="","",SUMPRODUCT(--EXACT(F2,$F$2:$F$8)))
I2 =IF(G2="","",SUMPRODUCT(--EXACT(G2,$G$2:$G$8)))
J2 =IF(F2="","Review store or day",IF(G2="","Review order ID",IF(I2>1,"Review duplicate order key","Ready")))
K2 =IF(J2="Ready",E2,"")

The zero patterns in F describe this four-digit code contract. Excel's TEXT function is used in two different ways. The first comparison verifies that the stored code would have the same four characters after a temporary numeric check and reformat. It does not write over the code. The second formats a real date for text output. Some languages localise format tokens or formula separators. Check the intended output using one known date before applying the expression to a normal report.

H counts groups among all source rows with usable store-day values. The 0042 group on 20 December appears three times even though these three records are currently on hold for order-level reasons. If you need a count of approved orders per day, use J as an inclusion condition and count only Ready records. Counting an identifier can help diagnose inputs. An approved summary still needs to respect the outcome decision.

Confirm the business rule behind a repeated combined key

In this exercise, the exact order key pair could be a repeated export row. It might also indicate an order-line file incorrectly treated as one order per row. Keep the two raw records. Get the source's definition and decide whether to use one validated copy or a field that distinguishes lines. If the verified replay is discarded from reporting, record which occurrence stayed and why. Do not drop one based solely on position or a convenience formula.

Try marking T06 as a separately verified order with ID O1006 on a disposable copy. Both records previously held as duplicate keys become unique under the stated rule, adding 520 to the approved total. Ready count becomes five and the approved sum is 1040.50. T05 and T07 still hold 140 in known raw amounts. This change is an instructional control. In a real handoff, retain the source confirmation for a corrected identifier.

Protect field boundaries when building a flat key

Concatenating AB and C without a divider yields ABC. Concatenating A and BC yields the same result. Adding a divider works only if the values cannot contain it or the representation defines safe escaping. For example, AB paired with C|D and AB|C paired with D both yield AB|C|D with naive joining. Prefer matching the separate fields if the tool supports that. If an export requires one flat key, define the permitted characters or a reversible encoding and verify it from the consumer's side.

Leaving out a part because it is blank can cause another collision. If a label is optional, TEXTJOIN's skip behavior can be useful. If every field position matters to an identifier, record the missing value's position or reject the incomplete key. Choose whether each ID is case-sensitive before making comparisons. EXACT and SUMPRODUCT here count literal matching strings in a bounded exercise range. This is useful when wildcard or case behavior of a different count formula would be inappropriate for the key contract.

4. Format numbers and dates explicitly inside a text result

Build a label that carries the right units

Imagine a campus organiser wants the line Store 0007 collected INR 320.50 on 20 December 2026. The raw code should already be text. The rupee amount should already be numeric, so the account workbook can still sum it. The date should already be a verified calendar value, so the organiser can filter the correct month. Use TEXT to convert each numeric value's presentation in the formula. Put the resulting sentence in a separate column and keep the source columns along with it.

="Store "&B2&" collected INR "&TEXT(E2,"0.00")&" on "&TEXT(C2,"dd mmmm yyyy")

This example uses row T01 and English display codes. Check that it reads Store 0007 collected INR 320.50 on 20 December 2026 in an intended English locale. Other locales may show a different decimal glyph or local month name. Agree the display with the audience. If the result is an interchange key rather than a reading label, specify a stable representation and validate it with the receiver. The source numeric amount 320.5 remains the same before and after creation of this label. The result cell is text and should not replace the numeric amount.

The exact order of joining operations matters. If a trip organiser has arrival date, an approved name and the number of nights, decide whether a missing night count should block the sentence or change it. A gap disguised as zero nights would alter the business meaning. Add a guard as you did for missing City. If you display one decimal and the input contains two decimals, the sentence may show a rounded value. Check whether the receiving report requires the original precision or a rounded display. Keep calculations on the numeric source rather than summing the rounded strings.

Check an error case in a disposable copy of the sentence. Replace the approved amount with an explanatory string such as Pending. The record no longer qualifies for the formula that expects a numeric amount. Choose a separate pending-message template where allowed, or withhold publication until the amount is verified. A sentence builder should not interpret arbitrary text as money. When checking templates, preserve even the unusual rows from the source so the team can see which message would be generated and which would be withheld. This also makes it easier to change the tone or punctuation of the printed line without changing the totals workbook.

Keep leading zeros from the source and only format known widths

Key formation should receive the exact identifier from its source. TEXT can display the numeric value 7 as 0007 when an explicit formatting policy calls for four digits. It cannot tell whether that code was originally 7, 07 or 0007. In the second lab 0007 enters as Text because the exact digits are part of the identifier. Use TEXT to format dates and amounts where presentation is requested. Restore lost key characters from the real source or a verified policy, rather than padding every value that looks short.

To see the type distinction, compare a cell containing 320.5 with an added formula =TEXT(E2,"0.00"). Treat the first as an amount and the second as a display token. ISNUMBER returns TRUE on the original and FALSE on the new text. Reapply a Number format to the original if the numeric column simply needs two visible decimals. That is enough to keep calculation and display together in a report table without a separate label. Use concatenation when one cell must carry multiple facts as readable text.

Manage blanks, spaces and error states separately

  • Blank is not a universal skip rule. For display labels a blank optional Area can disappear together with its delimiter. In a fixed position export an empty slot may need to stay. Check exactly how the receiving file expects empty fields.
  • Space is retained unless your cleanup says otherwise. A space-only cell may display like a blank but counts as input text. Inspect LEN or a validated trim helper. If internal spacing matters to a name or code, avoid broad normalisation.
  • Errors are evidence. A text join can propagate a source error. Find which source cell failed rather than telling the label to hide every error. Make an explicit status for affected records and keep their source ID.
  • Watch the result length. Excel cells have a text-length limit and TEXTJOIN returns a value error if the result exceeds 32,767 characters. A label called All orders assembled from a large range is rarely a useful report. Use bounded groups or a table whose rows preserve records.
  • Preserve repeatability. Flash Fill can create text via examples on supported builds, but its values do not recalculate after source edits. Verify names with spaces, missing fields and punctuation individually. A formula or a query is generally clearer when the same rule will be reused.

5. Decide between building a column and bringing in another table

Build a refreshable label with Power Query

When Power Query is available in the workbook, keep the source records and create a new text output column. Merge Columns consumes the selected text columns in that operation. You can duplicate them first or use an added custom column so the original fields remain available. The M function Text.Combine accepts a list of text values and ignores null items. A zero-length text value and a null are different input states. If your optional field can be either on import, map it into the approved missing representation explicitly rather than assuming they act the same.

if [City] = null or [City] = "" or [Platform] = null or [Platform] = "" then null
else [Platform] & " – " & Text.Combine(
    {if [Area] = "" then null else [Area], [City]}, ", "
)

This is an example custom expression with City, Platform and Area already typed as nullable text. It intentionally leaves a null label for missing City or Platform. Create separate review logic so a null label has an explainable reason. Test the full label, city-only label and two missing required cases before refreshing against a larger file. If a real numeric field must appear, decide the culture and format before turning that number into concatenated text. Availability and steps differ across Excel platforms.

Trace the row count when joining on store code

A Merge Queries step answers a different question: given an Order with Store code, what city or platform is recorded in the store reference table? The join should have one expected match for each code in this example. In the order table keep the amount and exact code. In the store reference table first confirm the uniqueness of its code, and check the text type on both sides. A composite match can use multiple fields in the same selection order. It does not require flattening them into one ambiguous string.

Try a tiny thought experiment. Three orders with stores 0007, 0007 and 0042 have amounts 12, 7 and 5. Together they sum to 24. The reference has two matches for 0007 and one match for 0042. After a left merge is expanded without a uniqueness check, the three order rows become five. The amount 12 appears twice, 7 appears twice, and 5 appears once. SUM now returns 43. The join kept the order records but added multiplicity. Grouping by the printed store label beforehand would not fix the reference table's duplicate key.

  1. Count matching reference rows for each order before expanding. A count of two needs a rule or correction when one was expected.
  2. Retain records with no match in a review path if the report needs every source row represented. A different join type could omit them entirely. Look at counts instead of relying on the visual impression of a table.
  3. After fixing the reference decision, compare the output's row count and amount to the original. In the toy example, expect three joined orders and 24 when the reference contains one approved match per code.
  4. Review the record grain after any intentional one-to-many join. Separate an order summary from a details table when amounts belong at the order level.

Append works when the second input supplies more records of the same grain. In Power Query, append aligns by column names, not by their visual position. A column missing from one source contributes nulls to its rows. For two monthly order files, confirm that fields with the same name have the same definition and type. The output count will reflect the appended population, including any replay across overlapping periods unless you address it explicitly. A text label does not solve those differences.

6. Check the new field before handing it to another person

Keep enough information to reproduce the rule

  • Describe the purpose. Name it Printed label, Daily grouping key or Candidate order identifier. A label called Merged may be reused without anyone knowing its scope.
  • Keep input fields and their types. Preserve text keys, numeric amounts and real dates. A downstream filter should not have to reparse a human greeting to recover its date.
  • Test two labels that look the same. One should be a legitimate display equality with two different stores. The other should be an order-key collision that requires a decision. The questions behind them are different.
  • Check blanks and separators. If your field is a report sentence, decide how to handle missing parts. For a consumed file check separator escaping, empty positions and code preservation.
  • Check the outcome counts. For the label lab expect five printed rows and two holds. For the orders lab expect three approved rows and four holds. If you export only approved records, identify that scope and keep the complete source separately.
  • Try a handoff with one sample. Paste a copy into the receiving tool with intended types. A CSV file does not automatically preserve all Excel type or formatting information. Confirm that the recipient still sees the exact code and can use the correct amount or date field.

For further practice choose an assembly task in the Excel Task Hub. Predict an exact result, including punctuation and date format. Then copy the fixture and add a missing optional value. Confirm which details are still available in the input even if the display label omits them.

Compare a display label with a reversible export field

Try using the display comma as a machine-readable separator. A consumer given Kothrud, East, Pune cannot know whether the area is Kothrud, East or just Kothrud without another rule. An optional Area omitted from a sentence can make the boundary even harder to infer. Keep separate columns whenever the receiving system supports them. If you provide only one composite field, write a format with defined escaping or verified part lengths. For example, a structured data format with separate named fields can carry punctuation and preserve the source facts for a later parser.

If a CSV file is required, use a proper exporter and inspect its output with the receiver's parser. Each field can be quoted, and an internal double quote in a quoted field is represented by two quotes. A label containing a comma can then arrive as one field. A format boundary is different from punctuation inside a label. Do not make a formula-generated piece of CSV and then export that piece as if it were already a row. The exporter may add an additional level of quoting to treat the whole string as a single field.

On a scratch grid, place Kothrud, East in A1 and 0007 as text in B1. To learn how quoting works, build a single raw text line with the example below. CHAR with 34 supplies a double quote. SUBSTITUTE doubles any internal double quotes first. The formula places commas only between the quoted fields. Under the stated CSV convention the result is two fields. The content of the first has an internal comma, and the content of the second has all four digits.

=CHAR(34)&SUBSTITUTE(A1,CHAR(34),CHAR(34)&CHAR(34))&CHAR(34)&","&CHAR(34)&SUBSTITUTE(B1,CHAR(34),CHAR(34)&CHAR(34))&CHAR(34)

With those two cells, the raw result should be "Kothrud, East","0007". Change A1 to Market "Blue" on the scratch sheet. The result now contains two consecutive double quotes on both sides of Blue inside its enclosing pair. A file parser interprets those doubled characters as single literal quotes. Compare this to the plain concatenation of A1, comma and B1. The latter does not create an unambiguous export for the original comma-bearing area. The point of this control is to verify how a second program understands your output, not to use a worksheet formula as a complete CSV writer.

Use short experiments to check what a new format will promise

Use a few cells to compare how your audience reads the same source fields. For a booking label, put room 101 in A2 and an actual 20 December 2026 date in B2. A joined string like 101-20261220 needs a literal hyphen and a verified text rendering of year, month and day. Then add a room stored as text 0101. The two room inputs may be distinct even if a number format would display them similarly. Check the resulting labels by comparing to the exact room registry. A consistent-looking format cannot repair a wrong source type.

Now try two recipient requirements. A colleague looking at a printout may want 20 December 2026 and the room on one line. A program may require date and room in two distinct fields with a documented type for each. Keep a suitable output for each use while retaining one verified source. If you later change a month name or add a currency symbol in the printed sentence, ensure the logic that identifies an order still receives the old verified fields. This keeps a presentation decision from rewriting a data relationship.

For a final handoff, record the exact test strings, their expected types after reimport and the source IDs. Ask the next analyst to recreate one complete label and one withheld key. If they can identify the blank Area as intentional, distinguish two same-day orders and keep 0007 intact, the worksheet carries enough evidence to be used beyond this lesson.

7. Interview questions with worked reasoning

How do you combine a city, area and platform into one label?

Keep all three fields and create a new output. TEXTJOIN can handle optional genuinely blank location parts within a common separator rule. Add the platform using an ampersand, and gate the resulting label on its required inputs. Source IDs still identify the underlying records.

What is the danger of Merge & Center on populated cells?

It changes the layout and retains only one cell's contents, deleting the other values in the merged range. It does not join the values as a string. Use a separate formula for the label and keep the originals for later inspection.

Why use TEXT inside a concatenation?

Joining a numeric date or amount directly need not preserve surrounding cell formatting. TEXT makes the chosen format part of the new string. The result is text, so keep the source date and amount for arithmetic and filtering.

Can store code and date be a primary order key?

That combination is generally appropriate for a store-day group and may identify a daily summary row. Several orders can share it. At order grain, include a verified order identifier and test uniqueness. At line grain a further verified line ID can be needed.

How would you investigate a total increasing after a merge?

Check how many reference matches each order had before expansion and compare input and output row counts. One-to-many matches can replicate amounts from the parent. Fix the reference key or calculate at the correct grain. Do not rely on removing identical looking text strings.

8. Predict the label, key or joined result

Area is blank for M04. What should its display label be?

FreshGo – Pune. TEXTJOIN skips the real blank area and does not leave an extra comma. The complete store identity remains available in the original Store code.

M01 and M07 print matching labels. Should you discard one?

Keep them both unless independent evidence says otherwise. They have different store codes, 0007 and 0391. A label repeated across records is permitted here and does not prove a replay.

Which records share 0007|20261220?

T01 and T02 share that store-day group and are distinct valid orders. IDs O1001 and O1002 supply different order keys. Adding their approved amounts gives 445.50 for that group.

Why reject O|1005 in the key lab?

The source contract forbids the separator inside an Order ID. Rejecting it makes the flat key's boundaries reliable for the receiving parser. Preserve its raw value and ask whether a revised or escaped representation is needed.

After expanding duplicate matches, why does a three-order example total 43 instead of 24?

The two 0007 rows repeat two times each. Their amounts are 12 and 7, and the 0042 row contributes 5 once. Expansion gives 12 plus 12 plus 7 plus 7 plus 5. Sum at one row per order or fix the unexpected reference duplication first.

9. Six reminders

  • Use a separate output field.

    Join text for reading while keeping the original typed fields available.

  • Choose punctuation deliberately.

    Skip genuinely empty optional fields only when that behavior fits the output.

  • Format numbers inside text.

    TEXT supplies the chosen display for verified numeric dates and amounts.

  • Define the key's grain.

    Store and date can group multiple orders. Verify uniqueness for the real record type.

  • Protect field boundaries.

    Only use a flat delimiter key when its parts cannot introduce confusing separators.

  • Track joins by match count.

    Check references before expansion so duplicate matches do not inflate sums.

Microsoft references