The government recorded a budget surplus last month for the first time since 2002 as more money came in from self-employed tax receipts.
July saw a surplus of £0.2bn, compared with last year's deficit of £0.3bn.
For the four months so far this year, though, public sector net borrowing - which leaves out support for public sector banks - was £1.9bn higher than last year's at £22.8bn.
July is the second most important month, apart from January, for tax revenue paid for by those completing self-assessment forms, such as the self-employed,
In both months, accrued receipts are higher because of receipts from self-assessed income tax.
This month, those receipts were the highest since records began in 1999.
July's receipts increased by £0.8bn, to £8bn, compared with July 2016.
No ease on squeeze
A Treasury spokesperson said: 'We are making good progress in strengthening our public finances and living within our means.
"Our national debt, at £65,000 for every UK household, is still too high. That is why we have a clear fiscal plan to reduce our debts and build a stronger economy for every household."
But Ruth Gregory, economist at Capital Economics, said the figures were probably just a blip, as the deadline fell on a different day of the week from last year.
"Self-assessment receipts were boosted by the 31 July deadline falling on a Monday this year, but Sunday in 2016, meaning that some receipts were recorded in August last year," she said.
She pointed out that so far, borrowing was still some 9% higher than the £20.9bn seen last year, with the OBR expecting this to worsen further.
"As such, despite July's strength, the chancellor may still find that he has little scope for any easing back on the planned fiscal squeeze in his November Budget."
The independent Office for Budget Responsibility (OBR) has forecast that public sector net borrowing will be £58.3bn during the financial year ending March 2018.
The ONS data showed that total government debt, excluding public sector banks, stood at £1.758 trillion at the end of July, which is equivalent to 87.5% of gross domestic product (GDP).