# Tables: Cell Color based on content / conditional cell coloring

I want a table to have red or green cell color, depending on the content: If the content is "a", make it green, if it is "b", make it red. BUT if the content is something else (e.g. in the column header) the cell should not be colored.

I can do the red/green thing if I only have the two options with the code below (which is based on this answer: https://tex.stackexchange.com/a/174359), but don't know how to stop it from coloring the column header.

\documentclass{article}
\usepackage{colortbl}

\begin{document}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{a}{\cellcolor{green}}{\cellcolor{red}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother

\begin{tabular}{C C C}
1 & 2 & 3 \\
\hline
a & b & a \\
b & b & b \\
a & a & b \\
a & a & a \\
\end{tabular}

\end{document}


Other questions have asked about this (e.g. Conditional Latex table: Cell value color based on its value) but they don't seem to solve my problem.

One way would be to add another \@ifnextchar in your conditional color definition:

   \documentclass{article}
\usepackage{colortbl}

\begin{document}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{a}{\cellcolor{green}}{\@ifnextchar{b}{\cellcolor{red}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother

\begin{tabular}{C C C}
1 & 2 & 3 \\
\hline
a & b & a \\
b & b & b \\
a & a & b \\
a & a & a \\
\end{tabular}

\end{document}

• Thank you, exactly what I was using for. I had tried something like this, but didn't know how to use it correctly. – Maria May 1 at 12:44