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}  
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.