This is easy to explain with diagrams, but I'll try. It uses only simple arithmetic and algebra.
If the subject is a distance u from the lens (warning: lenses are not a plane, so this should be distance from the front nodal plane, which isn't marked...) and the lens to image plane distance is v, then the magniication is the ratio of u and v.
If the object has a height h and the image a height j, then the magnification if j/h which is therefore equal to v/u.
The standard lens equation is 1/f = 1/u +1/v
From j/h = u/v, 1/v = j/hu
Substituting
1/f = 1/u + j/hu
For your example,
1/400 = 1/u + 24 (full frame height, landscape,or 36 if portrait, both approx)/300u
Assuming no slip in my algebra, rearrange to simplify and solve
300/400 = 300/u + 24/u
3/4 = 324/u
u = (324 × 4) / 3
u = 432mm
I sincerely hope someone will double check this - I'm rather tired and did this on screen rather than on paper...