Yes, so many that I'm only going to give one example of each or I'll be here all day.
Reasons to not use a ranged weapon include: stealth, conserving ammunition, not wanting to be lethal, close quarter combat, and (in the era of muzzle loaders) to have a repeating weapon.
Stealth
Forgoing loud, ranged weapons, specifically firearms, in favor of melee has a history about as long as firearms. You avoid shooting in order to cross a killing ground, and to surprise (or avoid) the enemy. The musical Hamilton describes a scene from the Battle of Yorktown.
Hamilton:
Get yo bullets out yo guns,
Get yo bullets out yo guns.
We move under cover,
And we move as one.
Through the night we have one shot to live another day.
We can not let a stray gunshot give us away.
We will fight up close,
Seize the moment and stay in it.
It's either that or meet the business end of a bayonet.
The code word is, 'Ro-Sham-Bo.'
Dig me'
Choirs:
Ro-Sham-Bo!
Hamilton:
You have your orders now,
Go man, go!
This is a whimsical, but accurate, description of Hamilton leading 400 light infantry in a sneak attack at dusk on British Redoubt 10. The British didn't take notice until the Americans were hacking at their wooden defenses with axes. Their stealth allowed them to cross a killing ground unmolested, avoiding casualties, and catching the British unprepared.
Stealth is by far the most common, guns go bang. They make a tremendous amount of noise audible for miles. A typical military rifle or pistol is in the 150-160 decibel range, louder than a jet engine at full power.
Silencers aren't silent. You don't just screw a thing on the end of a pistol like in the movies and get a little "PHOOT". They're more properly termed a "suppressor" reducing the noise and flash of the gun, but it still sounds like a gun. A good suppressor will reduce the noise to about 140 dB which is still extremely loud. Suppressors also come at a cost, reduced muzzle velocity meaning reduced range, accuracy and stopping power. There are a handful of actually silent guns out there, the Welrod pistol being the most famous, but this is a purpose designed weapon with many, many compromises for its level of silence.
Ammunition
Obviously if you run out of ammunition your ranged weapon is nothing but an awkward club. A smart commander who is running low on ammunition will hold their fire to conserve their limited ammunition for the most critical moments. Rather than firing on, say, a lone soldier, they will wait until there's a large group of troops. Or hold their ammunition in reserve until there's an enemy breakthrough.
Once you run out of ammunition, the enemy can move in the open with impunity. They can move their own artillery and support units closer and into better defensive position. So long as you have ammunition, even a little, you maintain the threat of firing back. Most armies are adverse to casualties and will not use attrition to run out an enemy's dwindling supply... unless you're the Soviets.
Towards the end of the Russo-Finish Winter War, the Finns ran critically low on everything, especially artillery ammunition. At the beginning of the war well sighted Finnish artillery had a field day firing at large masses of Soviet troops advancing across open and pre-sighted terrain. As the war went on, ammunition supply dwindled, and artillery had to choose their targets more carefully. Towards the end of the war, the Soviets could gather in the open for an attack and the Finns could not respond; they were reserving their dwindling ammunition for only the most critical moments. Artillerymen wept at these textbook targets. A week before the war ended the Finnish 2nd Corps had just 600 shells left in reserve for all guns.
Less-Than-Lethal
Pulling a gun means you're going to kill someone. There's no "I'll shoot the bad guy in the leg" or "I'll shoot the gun out of his hand", guns simply aren't that accurate, and you can bleed out or go into shock from any number of bullet wounds.
Using troops with rifles loaded with lethal ammunition as crowd control, especially if they have little training in crowd control, can have disastrous consequences, such as at Kent State when Armored Cavalry of the Ohio National Guard advanced on unarmed students with live ammo and fixed bayonets. Predictably they panicked and began firing their weapons killing 4 and injuring 9 civilians.
There's any number of situations where you need an equalizer, but don't want to risk death or even serious injury. Even well trained personnel can panic and fire their weapons into civilians. Any police action, particularly crowd and riot control, needs a less-than-lethal option. There have been any number of attempts to do this with firearms, but they all run into some fundamental trade-offs of accuracy, weight, and effectiveness.
Range and accuracy for a typical projectile is a function of weight and velocity. The faster the bullet, the further it will go, and the less it will drop. The heavier the bullet, the further it will go, and the less it will be affected by wind or soft barriers. The problem is fast and heavy also means more kinetic energy which means more chance of injury and accidental death. There's been any number of attempts to remedy this from Thompson Riot Ammo to modern Pepper-spray balls with various levels of success. The fundamental problem remains, you're still firing a high speed projectile at an unarmored person.
But when you come down to it, nothing beats the precision and control of a baton (assuming the person wielding it also has precision and control).
Close Quarter Combat
Military rifles, particularly prior to WWII, were very, very long and cumbersome. Black powder burns at a slower rate than modern smokeless powder and needs a longer barrel to get the full effect of powder charge. Even after the switch to smokeless powder, long barrels were retained to allow for a longer sight picture (ie. the distance between the rear and front sights) to allow for more accurate long range shooting. We now know this rarely happened, and modern military rifles are optimized for a max of 300 meters.
For example, the French Lebel and ubiquitous German Gewehr 98 (aka "the Mauser") were 1.3 meters long! These were later cut down into carbine versions like the Karabiner 98k, but still very long at 1.1 meters. The US WWII M1 Garand service rifle was also 1.1 meters. Even a modern M16 rifle is 1 meter long.
Add a bayonet that's up to half a meter long, and you can see how this rapidly gets unwieldy. Bayonets were designed to give musketeers a sort of pike to prevent massed cavalry charges (more on that below). This worked well against a massed charge into your fixed defenses, the enemy basically runs into a wall of blades, but they're terrible on the attack, especially into the tight spaces of a modern defensive position.
Such a long weapon is not very good in the tight spaces of a trench or building. InRangeTV has an excellent video demonstration of the limitations of bayonet fighting and the use of the knife, club, and spade in WWI trench fighting. Yes, a shovel like this Russian/Soviet MPL-50 entrenching tool makes a pretty nasty and ubiquitous close quarters weapon.
A long weapon made even longer with a bayonet limits how you can go around corners, through doors, or turn around. The long "shaft" of the rifle can be easily side-stepped and grabbed by your opponent turning it into a liability. In these cases a pistol or dedicated close-quarters rifle is much preferred, but many soldiers lack these. So they pack a short, brutal, often improvised melee weapon.
Modern armies are switching to even shorter weapons like the M4 carbine at 0.84 meters as their service rifle to ensure every soldier has a rifle that works in as many situations as possible.
Repeating Weapon
Finally, in the era of single shot muzzle loaders a melee weapon would be used simply because you couldn't reload your gun fast enough in the chaos of close quarter combat. This could be a bayonet, a sword, or even swinging your rifle like a club as in this popular (and probably not terribly accurate) painting of Davy Crockett in the Battle of the Alamo.
You fired your one shot, then switched to melee rather than try to take the 10 to 15 seconds to load with the enemy right in front of you. Even later breech loading weapons such as revolvers, tube magazine fed repeaters, and stripper clips were slow and awkward to reload in close combat. It wasn't until disposable, detachable box magazines became standard at the end of WWII that reloading in close quarters became really viable.
Naval Boarding Action
In the age of sail, a boarding action would be employed quite often as a decisive move. Until the advent of explosive shell in the latter half of the 19th century, cannon were inaccurate and not terribly effective against even wooden hulled warships. Ships could pound away at each other for hours without decisive result. Often the enemy ship was grappled and a boarding party sent over.
There were a great many reasons to prefer a boarding action to a gun battle until the enemy struck their colors.
Outgunned
In the age of sail, a vessel which found itself outgunned and unable to run away, or duty bound to fight, might consider a boarding action instead. The captain would be gambling that their crew could fight harder than the enemy crew. The British often employed this tactic. In addition to carrying a contingent of Royal Marines (ie. professional soldiers) their crews were often better trained and had higher morale than your average French, Spanish, or civilian crew.
Thomas Cochrane's capture of the 32 gun Spanish frigate El Gamo from his 14 gun sloop HMS Speedy is a good example. He approached under the neutral American flag, a common tactic at the time. By the time Speedy raised her battle ensign she was close that El Gamo could not depress her guns to fire on his much smaller vessel while Speedy fired into El Gamo's crew. Despite being outnumbered 5-to-1, Speedy took El Gamo by boarding action.
Jack Aubrey of the Master & Commander series is based on Thomas Cochrane. The movie Master & Commander: The Far Side Of The World shows a fictional but fair amalgamation of this action at its climax.
Take The Vessel Intact
If you were a privateer, or in a navy that offers prize money for captured vessels, you probably didn't want to smash your payday to pieces with cannon. In this case, a boarding action is called for.
In the more modern era, a raider might wish to plunder its prize for supplies, fuel and food. The more supplies they can capture and use, the longer they can remain a threat at sea, and the further they can roam.
In the case of a smaller and/or faster vessel, the hunter may employ trickery to get close to its prey and grapple to prevent their prey from escaping.
Finally, simple humanitarian and legal reasons would preclude firing on an enemy merchant vessel. At the opening of WWI and WWII, raiders and submarines followed international law requiring unarmed ships be stopped and searched for contraband and their crews be given time to evacuate before sinking. This process was slower. It left the raider stopped and vulnerable, particularly a submarine on the surface. And it allowed the merchant the opportunity to transmit a warning signal.
Conserve Ammunition
Ships at sea have a limited supply. While a raider can resupply common items like fuel and food from captured vessels, specialized supplies such as ammunition cannot be plundered. Once a raider runs low on ammunition, they must return home removing themselves as a threat. A good raider will capture and sink vessels by boarding action as often as possible.
The exploits of German raiders at the opening of WWI and WWII exemplify these tactics. Greatly outnumbered by the British navy, and seeking to do as much damage as possible to Allied shipping before their inevitable destruction, independent German raiders used all these tactics to get the most out of their ships.
Pinguin
The ship which most exemplifies these ideas is the German auxiliary cruiser Pinguin. Basically a freighter with guns, she had no hope of fighting off a real warship, but lasted a year traveling 60,000 miles sinking or capturing 150,000 gross tons. She captured 16 ships, and sunk 6 with a boarding crew to plant explosive charges. She plundered ships for fuel and food, sometimes sending them back to Germany. She used captured ships as auxiliaries to lay mines, resupply, or act as decoys. Pinguin would even use her seaplane to snatch away a target's radio antennas before they could broadcast a warning.
Her exploits capturing a Norwegian whaling fleet are worth studying. Upon discovering two Norwegian factory ships in service of the British were stopped transferring oil, Pinguin snuck along side and captured the vessels without incident, including their whaling boats. They told the crews to continue working with the assurance they'd be paid by Germany (Norway was still neutral). Without a single shot fired and no casualties, they captured 36,000 tons of shipping and 30,000 tons of oil.
Ramming Speed!!!
Throughout naval history, particularly before effective cannon were developed, the ram has proven decisive. Most warships were designed with a "ram bow" to pierce the enemy vessel below the water line. This practice continued even into WWI when the ram bow was eventually replaced by a more hydrodynamic bow.
Ramming remained a common tactic against submarines. While a submarine's inner pressure hull is very strong, their outer hull which provides buoyancy is fragile. Even a diving submarine is vulnerable to being rammed by the large portion of the attacking vessel which is below the water. Before the advent of depth charges, for many warships and merchant vessels ramming was their only means of attacking a diving submarine.
Finally, desperate tank crews might ram the enemy. If they found their cannon knocked out, or out of ammunition, or simply unable to penetrate the enemy. Desperate tank crews, particularly Soviet, would ram the enemy. The Battle of Prokhorovka (the huge tank battle portion of Kursk) featured confused close quarters tank combat and ramming.