1

I'm writing a questionnaire in LaTeX, and want to make a macro for questions. One feature I want is to cross-reference questions using labels (e.g. in case you want to skip a question. Here's a MWE of what I have so far:

\documentclass{article}
\usepackage{tabu,textcomp,amsmath,longtable}
\usepackage[left=2cm, right=2cm, top=2cm]{geometry}

\newcounter{qnumber}
\setcounter{qnumber}{0}
\stepcounter{qnumber}

\newcommand{\question}[3]{
\hfill \theqnumber\hfill\hfill & #1 & #2 & #3\stepcounter{qnumber}\\ \hline
}

\begin{document}

\begin{longtabu} to \textwidth {|c|X|X|X|}
\hline
\textbf{Sl.} & 
\textbf{Question text} & 
\textbf{Instructions for enumerator (not to be read out)} &
\textbf{Response options} 
\\ \hline

\question{What is your age?}{Enter age in years}{18--99}    
\question{Do you rent your house?}{}{1. Yes; 2. No}    

\end{longtabu}
\end{document}

What I would like is to have another set of curly braced in \question where a label can be given to the question, which then allows for cross referencing of question numbers. For example:

\question{Do you rent your house}{lab:rent}
\question{If you answered "Yes" in question \ref{lab:rent}, how much do you pay per month} 

How can I adapt the \newcommand line to make this work?

3

You can, for example, use an optional argument to \question which becomes the label if not empty:

\documentclass{article}
\usepackage{tabu,textcomp,amsmath,longtable}
\usepackage[left=2cm, right=2cm, top=2cm]{geometry}

\newcounter{qnumber}
\setcounter{qnumber}{0}

\newcommand{\question}[4][]{%
  \refstepcounter{qnumber}%
  \if\relax\detokenize{#1}\relax
  \else
    \label{#1}%
  \fi
  \hfill\theqnumber\hfill\hfill & #2 & #3 & #4\\ \hline
}

\begin{document}

\begin{longtabu} to \textwidth {|c|X|X|X|}
\hline
\textbf{Sl.} & 
\textbf{Question text} & 
\textbf{Instructions for enumerator (not to be read out)} &
\textbf{Response options}
\\ \hline

\question{What is your age?}{Enter age in years}{18--99}
\question[lab:rent]{Do you rent your house?}{}{1. Yes; 2. No}
\question{If you answered "Yes" in question \ref{lab:rent}, how much do you pay per month}{}{}

\end{longtabu}
\end{document}

enter image description here

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.