Calculating Compressibility factor from the Van der Waals' Gas equation
$$Z = \frac{V^{\mathrm{r}}_{\mathrm{m}}}{V^{\circ}_{\mathrm{m}}}\tag{1}\label{1}$$

$V^{\mathrm{r}}_{\mathrm{m}} = \text{Volume of 1 mol real gas.}$

$V^{\circ}_{\mathrm{m}} = \text{Volume of 1 mol perfect gas.}$

The van der Waals equation is $$ \left( P^{\text{r}} + \frac{an^2}{(V^{\text{r}})^2}\right) (V^{\text{r}} - nb ) = nRT \tag2\label{2}$$

Now, consider you have a container containing a $1~\mathrm{mol}$ real gas. You know its pressure $P^{\text{r}}$, volume $V^{\text{r}}$ and temperature $T$ and you wish to find the compressibility factor of this gas. 

So, for calculating $Z$, we know the real volume of the gas, i.e $V^{\mathrm{r}}$ and now we need to calculate  $V^{\circ}$ which is the volume it should have occupied if it behaved like a perfect gas, i.e. it obeyed the perfect gas law.

Thus, $$V^{\circ} = \frac{RT}{P^{\text{r}}}$$

Therefore, substituting this value of $V^{\circ}$ in $\eqref{1}$ $$Z = \frac{V^{\mathrm{r}} P^{\text{r}}}{RT}\tag3\label{3}$$

From $\eqref{2}$, by rearranging the terms, we get $$P^{\text{r}} = \frac{RT}{(V^{\text{r}} - b)} - \frac{a}{(V^{\text{r}})^2} \tag4\label{4}$$

Substituting this value of $P^{\text{r}}$ in $\eqref{3}$, we get $$Z = \frac{V^{\text{r}}}{(V^{\text{r}} - b)} - \frac{a}{V^{\text{r}}(RT)} \tag5\label{5}$$