透過具有可選參數的巨集定義多列

透過具有可選參數的巨集定義多列

我嘗試為快捷方式定義巨集\multiline{1}{<pcolumn type>}{\textbf{text}}

\documentclass[12pt,border=1mm,preview]{standalone}

\newcommand\mcbf[2]{\multicolumn{1}{#1}{\textbf{#2}}}
    \begin{document}
\begin{tabular}{lr}
    \hline
\mcbf{|c|}{AAA}  &   \mcbf{c|}{BBB}   \\ \hline
\end{tabular}
    \end{document}

哪個按預期工作。由於在大多數情況下我使用相同的列說明符,我嘗試重新定義此宏,因此預設列類型是例如c|

\documentclass[12pt,border=1mm,preview]{standalone}

\newcommand\xmcbf[2][c|]{\multicolumn{1}{#1}{\textbf{#2}}}

    \begin{document}
\begin{tabular}{lr}
\xmcbf[|c|]{AAA} &   \mcbf{BBB}  \\ \hline
C                &   D           \\ \hline
\end{tabular}
    \end{document}

這給了錯誤:

\multispan ->\omit
                  \@multispan

我在\newcommand定義中錯過了什麼?我在 SE 中的搜尋(可能很笨拙)沒有提供有用的信息。

答案1

你需要命令擴張\multicolumn

\documentclass[12pt,border=1mm,preview]{standalone}
\usepackage{xparse}

\DeclareExpandableDocumentCommand\xmcbf{O{c|}m}{\multicolumn{1}{#1}{\textbf{#2}}}

    \begin{document}
\begin{tabular}{lr}
\xmcbf[|c|]{AAA} &   \xmcbf{BBB}  \\ \hline
C                &   D           \\ \hline
\end{tabular}
    \end{document}

相關內容