Mega 2560 Rev. 3: Not Working Without Initial USB Connection

I am running into a problem with my Mega project. It's only working if I have an external power source plugged in, as well as a USB connection. The USB can then be unplugged, leaving a 9V to keep it going. However, the Arduino seems to be unable to run the code if the 9V is ever unplugged, and plugged in without the USB connection.

I have read other stories of people not having enough power to begin with, but this seems to be another issue.

I got it working again, I think it was a flaw in my code.

Fourest:
I got it working again, I think it was a flaw in my code.

Good to hear that it's 'working' again. Although, the word 'working' that was used in the original post is kind of vague. The description of the problem wasn't very clear at all. Were you trying to say that if you begin with a bare unpowered arduino, and then you connect a USB cable to it, then your arduino would remain unpowered (ie. no power to it)? From the original post....nobody knows what you meant about 'working' or 'not working'......due to lack of details.

Good to hear that it's 'working' again. Although, the word 'working' that was used in the original post is kind of vague. The description of the problem wasn't very clear at all. Were you trying to say that if you begin with a bare unpowered arduino, and then you connect a USB cable to it, then your arduino would remain unpowered (ie. no power to it)? From the original post....nobody knows what you meant about 'working' or 'not working'......due to lack of details.

Working....

Start with 5V and USB, both connected to the Arduino.
Sketch works perfectly.
Disconnect the USB, leaving the 5V connected.
Sketch continues to work.
Leave the USB disconnected, and unplug and replug or turn off and on the 5V.
Sketch fails to run, resulting in a visual error, (Arduino is powering LEDs.)
Basically the Arduino would lose it's ability to run the Sketch, or from my opinion: Save the Sketch, if the 5V was disconnected. Plugging in the USB cable would "save" the sketch until all power is lost.

Your posts are confusing.

You talk about external 9volt and USB, and then you talk about 5volt and USB.
And you didn't mention where you have connected external supply to.

A Mega needs an absolute minimum of 6.6volt on the V-in pin, or 7.3volt on the DC socket (including dips).
5volt external can be connected to the 5volt pin, but that could give unexpected results in combination with USB supply.

A sketch is saved to flash during upload, and does NOT change until you upload a new sketch.
A bad supply could reset/corrupt the Mega during bootup, but that does not affect the stored sketch.

Not sure what else you have attached to the Mega's 5volt pin.
I hope not the 152 addressable LEDs you mentioned in another thread.
Post a connection diagram, and exact specs of the supply.
Leo..