# Error with \newcommand using \multicolumn in table

I want to define a new command \tableheadline that (1) formats the headline text in some way and (2) takes an optional argument for spanning multiple columns while centering the headline. I tried the following implementation:

\documentclass{minimal}

\begin{document}
\begin{tabular}[\textwidth]{cc}
0 & 1 \\
2 & 3 \\
\end{tabular}
\end{document}


This, however, gives me an error:

! Misplaced \omit.
\multispan ->\omit
\@multispan


I also get the error when I do not even use the optional argument (see commented line in the MWE). Any ideas what I am doing wrong?

• This seems to be similar: tex.stackexchange.com/questions/67947/… – koleygr Jul 2 '18 at 14:57
• Unfortunately, I couldn't figure out a solution based on the linked thread, yet. Is this obvious for you? – seyfe Jul 2 '18 at 15:34
• Just said that this is a similar question... Didn't manage to make it work but is still similar (source of the problem is the one mentioned by egreg in his answer: His answer works if you add a \\ that you missed in the end of first tabular line) – koleygr Jul 2 '18 at 15:40
• Yes, that's true. Good spot! – seyfe Jul 2 '18 at 20:08

A command with optional argument stops the scanning for \omit and starts a cell; when \multicolumn is then seen it's too late.

You can use xparse, though:

\usepackage{xparse}


This is only possible when the optional argument is not the last argument in the list, but this is your case.

Full example:

\documentclass{article}
\usepackage{xparse}

\multicolumn{#1}{c}{\textit{#2}}%
}

\begin{document}

\begin{tabular}{cc}
0 & 1 \\
2 & 3 \\
\end{tabular}

\end{document}


Notes.

1. [\textwidth] does nothing at all: the optional argument can be t, b or c, anything else is ignored.

2. You were missing \\ for ending the first row.

3. Don't use minimal for examples.

• Does this compile for you with the MWE in the original question? For me, it doesn't :/ – seyfe Jul 2 '18 at 15:36
• @seyfe Yes, it does, provided you fix the missing \\. – egreg Jul 2 '18 at 16:05
• Oh yes thanks a lot! The \textwidth was a remainder of the tabularx environment, I was using before. The missing \ was key! Why shouldn't one use minimal? I thought it is used for debugging purposes. – seyfe Jul 2 '18 at 20:08