Figures from the Office for National Statistics showed the government's finances were in surplus by £2bn last month.
The figure was up from a surplus of £1bn in July last year.
Economists had been expecting a surplus of £1.1bn.
Treasury coffers were boosted by increases in self-assessment and other tax receipts last month, according to the ONS data.
Borrowing for the financial year reached £12.8bn - the lowest for 16 years - and £8.5bn less than during the same period in 2017.
The Chancellor tweeted: "We can't be complacent, we must keep debt falling to build a #StrongerEconomy and secure a brighter future for the next generation."
Public sector net debt - which strips out the impact of bailed-out banks - was £1,777.5bn at the end of July.
This is the equivalent to 84.3% of gross domestic product (GDP) and an increase of £17.5bn on July 2017, but 1.7% lower as a percentage of GDP as it was 86% a year ago.
Experts said an improvement in public finances could make it easier for the chancellor to find the extra funds promised for the NHS without cutting back elsewhere, when he delivers his autumn statement later this year.
Ruth Gregory, a senior economist at Capital Economics, said: "As things stand, the chancellor should have some extra money to play with in the autumn Budget - on top of the scope already contained within his fiscal mandate.
"He should be able to deliver the extra funds for the NHS without compromising his fiscal target or having to find savings elsewhere."
The Treasury said: "We have made great progress repairing the public finances.
"Thanks to the hard work of the British people, government borrowing is down by three quarters and debt is due to begin its first sustained fall in a generation."
More from Philip Hammond
Chancellor Philip Hammond considering 'Amazon tax' for online retailers
Philip Hammond: Chequers plan 'best way forward' on Brexit
Philip Hammond defends May's Brexit plan after City's rebuttal
Philip Hammond gave us Tigger - but he probably should have been more Pooh
Saved! Future of 1p and 2p coins rescued amid backlash
Spring statement 2018: Upgraded growth and borrowing sees Philip Hammond hint at spend boost
Shadow chancellor John McDonnell said Mr Hammond had "passed on the deficit to his colleagues in other departments: record NHS deficits, schools begging parents for money for essentials, and a growing social care crisis".
He said: "Hard pressed families and underpaid public sector workers have been made to pay for the price of Tory failure on the economy, with brutal cuts to social provision and relentless pay restraint."