5. Let $S_{n}$ be the sum of the first $n$ terms of the arithmetic sequence $\left\{a_{n}\right\}$, $S_{9}=18$, $a_{n-4}=30(n>9)$, $S_{n}=336$. Then the value of $n$ is ( ).
(A) 16
(B) 21
(C) 9
(D) 8
5.B.

From $S_{9}=18$, we have $\frac{9\left(a_{1}+a_{9}\right)}{2}=18$, which means $a_{1}+a_{9}=4$, hence $2 a_{5}=4, a_{5}=2$.
$$
\text { Also } \begin{aligned}
S_{n} & =\frac{n\left(a_{1}+a_{n}\right)}{2}=\frac{n}{2}\left(a_{5}+a_{n-4}\right) \\
& =\frac{n}{2}(2+30)=336,
\end{aligned}
$$

thus $n=21$.