[Tex/LaTex] How to include tabularx/y in a new environment

environmentstablestabularx

I am looking for a way to define a customizable environment for tables in my latex documents. This means:

  • caption and label
  • width of table
  • customized column format (tabular preamble)

While this seems to be easy for figures, I am desparately looking for a solution for tables. Here is my minimal code example:

\documentclass[a4paper,fontsize=14pt,DIV=calc]{scrbook}
\usepackage{tabularx,tabulary}

\newenvironment{tabfig}[4]
{\begin{table}
 \captionabove{#2}\label{tab:#1}
 \begin{tabularx}{#3}{#4}}
{\end{tabularx}\end{table}}

\begin{document}
  \begin{tabfig}{MyLabel}{MyCaption}{0.8\textwidth}{l >{\centering}X >{\centering}X}
    A & B & C \tabularnewline
    x & y & z \tabularnewline
  \end{tabfig}
\end{document}

I have done thorough research for several days by now and also tried \bgroup, \begingroup, \begintabularx, the cprotect package and various other things. Though, I could not come up with something useful in this general case. Folks, I cannot believe I am the first to write a customizable table environment. Is there anybody to light the light?

Best Answer

Try this:

\documentclass[a4paper,fontsize=14pt,DIV=calc]{scrbook}
\usepackage{tabularx,tabulary}

\newenvironment{tabfig}[4]{%
     \table\centering%
     \captionabove{#2}\label{tab:#1}%
     \tabularx{#3}{#4}%
}{%
     \endtabularx%
     \endtable%
}%

\begin{document}
\begin{table}
 \captionabove{MyCaption}\label{tab:MyLabel}
 \begin{tabularx}{0.8\textwidth}{l >{\centering}X >{\centering}X}
    A & B & C \tabularnewline
    x & y & z \tabularnewline
\end{tabularx}\end{table}

  \begin{tabfig}{MyLabel}{MyCaption}{0.8\textwidth}{l >{\centering}X >{\centering}X}
    A & B & C \tabularnewline
    x & y & z \tabularnewline
  \end{tabfig}
\end{document}