Context. Cosmic rays and solar energetic particles induce changes in the composition of compounds frozen onto dust grains in the interstellar medium (ISM), in comets, and on the surfaces of atmosphere-less small bodies in the outer Solar System. This induces the destruction of pristine compounds and triggers the formation of various species, including the precursors of complex organics. Aims. We investigate the role of energetic ions in the formation of formaldehyde (H 2 CO) and acetaldehyde (CH 3 CHO), which are observed in the ISM and in comets, and which are thought to be the precursors of more complex compounds such as hexamethylenetetramine (HMT), which is found in carbonaceous chondrites and in laboratory samples produced after the irradiation and warm-up of astrophysical ices. Methods. We performed ion irradiation of water, methanol, and ammonia mixtures at 14-18 K. We bombarded frozen films with 40-200 keV H + that simulate solar energetic particles and low-energy cosmic rays. Samples were analysed by infrared transmission spectroscopy.Results. Among other molecules, we observe the formation of H 2 CO and CH 3 CHO, and we find that their abundance depends on the dose and on the stoichiometry of the mixtures. We find that the H 2 CO abundance reaches the highest value after a dose of 10 eV/16u and then it decreases as the dose increases. Conclusions. The data suggest that surfaces exposed to high doses are depleted in H 2 CO. This explains why the amount of HMT in organic residues and that formed after irradiation of ices depends on the dose deposited in the ice. Because the H 2 CO abundance decreases at doses higher than 10 eV/16u, a lower quantity of H 2 CO is available to form HMT during the subsequent warm-up. The H 2 CO abundances caused by ion bombardment are insufficient to explain the ISM abundances, but ion bombardment can account for the abundance of CH 3 CHO towards the ISM and comets.