Quantum error correction is believed to be a necessity for large-scale fault-tolerant quantum computation. In the past two decades, various constructions of quantum error-correcting codes (QECCs) have been developed, leading to many good code families. However, the majority of these codes are not suitable for near-term quantum devices. Here we present VarQEC, a noise-resilient variational quantum algorithm to search for quantum codes with a hardware-efficient encoding circuit. The cost functions are inspired by the most general and fundamental requirements of a QECC, the Knill-Laflamme conditions. Given the target noise channel (or the target code parameters) and the hardware connectivity graph, we optimize a shallow variational quantum circuit to prepare the basis states of an eligible code. In principle, VarQEC can find quantum codes for any error model, whether additive or non-additive, degenerate or non-degenerate, pure or impure. We have verified its effectiveness by (re)discovering some symmetric and asymmetric codes, e.g., ((n,2n−6,3))2 for n from 7 to 14. We also found new ((6,2,3))2 and ((7,2,3))2 codes that are not equivalent to any stabilizer code, and extensive numerical evidence with VarQEC suggests that a ((7,3,3))2 code does not exist. Furthermore, we found many new channel-adaptive codes for error models involving nearest-neighbor correlated errors. Our work sheds new light on the understanding of QECC in general, which may also help to enhance near-term device performance with channel-adaptive error-correcting codes.