I am also working on this problem. Currently I found three variants:
1. Two types of units. Create a unit that in nearly the same, except the attack. Set an event that detect melee attack*. Then order attacked unit to transform into a melee variant via triggers. After some time order it to transform back in ranged.
Cons: If unit is given a command via triggers it will forget it current order, so if you use attack-move, melee unit will stand still while other will go forward.
2. Drunken Haze. Make your unit two attacks, first ranged, second melee. Create a dummy unit with cast animation** set to 0 with drunken haze ability. Check in data - attacks prevented 'Ranged' flag, area effect less than or equal to 100, missile speed to 0 and nullify other negative effects (in data). Set that event* and order dummy unit to cast drunken haze on attacked unit.
Variant: you can add ability drunken haze with nullified effect (except ranged thingy) to ALL melee unitS, but do not think this is a good idea.
Cons: Drunken haze is a spell, thus CAN be dispelled. However it is better than its Silence variant as the AI (computer controlled and autocast spells) will not acquire it. But if you plan to make a map like napoleonic warfare when no magic is used it is fine.
3. War Club. This is the only ability that set enables and disables attacks directly. However the requirement to target and destroy a tree makes it useless here.
* - Actions:
Generic Unit Event - Unit is (attacked)
- Conditions:
(Attacking Unit) type equal to (your unit)
- Actions:
....
** Animation - Cast backswing/...
Hope it helps!