2

I'm creating many tables and want to change the colour of text if it is in a certain area to red, see the image below for my example:

enter image description here

For this, I want any cell which is an intersection of lettered columns or rows (the ones with red characters or blank cells) to have red text in them.

This is what my code for it looks like:

\begin{center}
\begin{tabular}{ |c|c|c|c|c|c| }
\hline
&W&X&Y&Z&Stock\\
\hline
A&\textcolor{red}{11}&\textcolor{red}{3}&&&14\\
\hline
B&&\textcolor{red}{12}&\textcolor{red}{4}&&16\\
\hline
C&&&&&20\\
\hline
Demand&11&15&14&10&50\\ 
\hline
\end{tabular}
\end{center}

This works but is is very time consuming to do \textcolor{red}{number} every time. Is there any shortcut for this?

  • you can always use \def\cred#1{\textcolor{red}{#1}} in your preamble (or latter). Also \newcommand{\cred}[1]{\color{red}#1} will do the same... and then just \cred{12} is enough. In latex you can define your own commands. – koleygr Oct 20 '17 at 10:26
  • What would be the exact criteria for colouring text? – Bernard Oct 20 '17 at 11:35
  • See also https://tex.stackexchange.com/questions/65649/counters-for-use-in-array-tabular-cells – John Kormylo Oct 20 '17 at 14:58

2 Answers2

2

Define the columns where you want coloring and set up a mechanism for disabling and enabling coloring.

\documentclass{article}
\usepackage{xcolor,array}

\newcommand{\docolor}{\ifcoloring\color{red}\fi}
\newif\ifcoloring
\newcommand{\startcoloring}{\global\coloringtrue}
\newcommand{\stopcoloring}{\global\coloringfalse}

\begin{document}

\begin{tabular}{|c| *{4}{>{\docolor}c|} c| }
\hline
\stopcoloring
&W&X&Y&Z&Stock\\
\hline
\startcoloring
A&11&3&&&14\\
\hline
B&&12&4&&16\\
\hline
C&&&&&20\\
\hline
\stopcoloring
Demand&11&15&14&10&50\\ 
\hline
\end{tabular}

\end{document}

enter image description here

egreg
  • 1,121,712
1

Some command definitions in the preamble for coloring:

\documentclass[a4paper, 11pt]{article}
\usepackage[table]{xcolor}

\def\cred#1{\textcolor{red}{#1}}
\newcommand\colr{\color{red}}
\def\mybluecell{\cellcolor{blue!30}}

\begin{document}


\begin{tabular}{ |c|c|c|c|c|c| }
\hline
&W&X&Y&Z&Stock\\
\hline
A&\cred{11}&\textcolor{red}{3}&&&14\\
\hline
B&&\colr 12& \mybluecell 4&&16\\
\hline
C&&&&&20\\
\hline
Demand&11&15&14&10&50\\ 
\hline
\end{tabular}
\end{document}

You can use short names to be easier for you to write the command.

Output:

enter image description here

koleygr
  • 20,105