Quantum systems can be exquisite sensors thanks to their sensitivity to external perturbations. This same characteristic also makes them fragile to external noise. Quantum control can tackle the challenge of protecting quantum sensors from environmental noise, while leaving their strong coupling to the target field to be measured. As the compromise between these two conflicting requirements does not always have an intuitive solution, optimal control based on numerical search could prove very effective. Here we adapt optimal control theory to the quantum sensing scenario, by introducing a cost function that, unlike the usual fidelity of operation, correctly takes into account both the unknown field to be measured and the environmental noise. We experimentally implement this novel control paradigm using a Nitrogen Vacancy center in diamond, finding improved sensitivity to a broad set of time varying fields. The demonstrated robustness and efficiency of the numerical optimization, as well as the sensitivity advantaged it bestows, will prove beneficial to many quantum sensing applications. arXiv:1712.08256v1 [quant-ph]