When Allah says that He will guide whom He wills, it reminds us to be humble. We cannot consciously choose guidance in the same way that we might go to a shop and buy bread. Nor do we deserve it automatically.
Rather, guidance - like faith, wisdom, and other intangibles - is a gift bestowed upon us by the divine, and is something we should be grateful for, rather than arrogantly thinking that we determined it on our own.
However, these intangibles - like guidance, faith, and wisdom - are not bestowed on people randomly. They are similar to plants growing from a seed. A person can prepare the ground, plant the seed, water the plant, and so on, but after they have done everything they can, all they can do is pray that the plant will grow well. However, that person will have a much better chance of the plant growing than someone who simply throws a seed on the ground in the desert and ignores it.
Similarly, we can prepare the ground of our hearts to receive guidance, etc, by sincerely seeking the truth; acting honestly, genuinely, and humbly; putting forth eforts to seek knowledge, and the like. Thus we "earn" guidance - but, of course, we are reminded that we cannot force it through our actions.
Conversely, some people disqualify themselves from guidance by indulging in evil, destroying their souls, being arrogant, or doing other things which seal their hearts. They would not benefit from the guidance even if a tablet descended to them from the heavens because they are not ready to receive it.
Allah is just, merciful, and all-knowing and would not deprive someone of guidance unjustly.
It is an excellent question to ponder however!
You can find more discussions of this question in the tafsir of the relevant ayat.