4

In the MWE below there are two tables. Both sould end up the same. But there is a problem in the second table (Error: Misplaced \omit). \multicolumn{2}{|l|}{#1} \\ \hline does not work in my new command. How can I fix it?

\documentclass{article}
\usepackage{booktabs}
\usepackage{ifthen}

\newcommand{\newcol}[2]{
\ifthenelse{\equal{#2}{}}{
\multicolumn{2}{|l|}{#1} \\ \hline
}{
#1 & #2\\ \hline
}
}

\begin{document}

\begin{tabular}{|c|c|}
\hline
\multicolumn{2}{|l|}{Title} \\
\hline 
x (mm) & 10\\
\hline
y (mm) & 12\\
\hline
\end{tabular}

\begin{tabular}{|c|c|}
\hline
\newcol{Title}{}
\hline 
\newcol{x (mm)}{10}
\newcol{y (mm)}{12}
\end{tabular}
\end{document}  
Sebastiano
  • 54,118

1 Answers1

4

The \ifthenelse text makes TeX begin a new table cell, so \multicolumn comes too late. Use an “expandable test”.

\newcommand{\newcol}[2]{%
  \if\relax\detokenize{#2}\relax
    \multicolumn{2}{|l|}{#1} \\ \hline % empty second argument
  \else
    #1 & #2\\ \hline
  \fi
}

See What does \ifx\\#1\\ stand for? for some more information on the test used above.

egreg
  • 1,121,712