Voltaire's aphorism first appeared in the Epistle to the Author of "The Three Impostors" (1769), see Voltaire and Religion. The author was an atheist and the "three impostors" were Moses, Jesus and Mohammed. According to Voltaire's contemporaneous letter to his niece:
"This morning I had fun writing an epistle against the book of the three impostors. I have just finished it. I will send it to you. I believe atheism is as pernicious as superstition."
Voltaire repeated the quip in the Speech by Me. Belleguier (1773), along with an explanation that praises himself in the third person:
"The astronomer who whatches the motions of stars, established according to the laws of the most profound mathematics, must adore the Eternal Geometer. The physicist who investigates a grain of wheat or an animal body must recognize the Eternal Craftsman. The moral man who seeks a support point in virtue must admit the existence of a Being as fair as He is supreme. So God is necessary to the world in every way, and we can say together with the author of the Epistle to the scribbler of a vulgar book on the Three Impostors, "If God did not exist, it would be necessary to invent Him"."
Apparently, Voltaire felt that the order in nature and the moral law suggest a higher power as their source, the sort of "god of poets and philosophers" in deism. It was a popular position during the age of Enlightenment, which Voltaire himself espoused. His explanation echoes Kant's equally famous quip:
"Two things fill the mind with ever new and increasing admiration and awe, the more often and steadily we reflect upon them: the starry heavens above me and the moral law within me."
Kant gave a sophisticated philosophical explanation of the inference as the tendency of our reason to posit transcendent entities that "unify experience", see SEP. Although he criticized metaphysical speculations about such entities as "transcendental illusion", his philosophy of practical reason also alludes to a "support point in virtue" and philosophy of judgment endorses "purposiveness of nature".
An anecdote in the same spirit is Lagrange's alleged reply to Laplace's remark that he "did not need this hypothesis" (God) in celestial mechanics:"Ah, but that is a fine hypothesis. It explains so many things."