He said Scotland was the source of some of his happiest memories, but also his saddest.
The prince was addressing the opening session of the Church of Scotland's General Assembly which he is attending as Lord High Commissioner, the Queen's representative.
He said: "Scotland is incredibly important to me and will always have a special place in my heart. I've been coming to Scotland since I was a small boy.
"As I grew up I saw how my grandmother relishes every minute she spends here and my father is never happier than in walking among the hills.
"My childhood was full of holidays having fun in the fresh air, swimming in lochs, family barbecues with my grandfather in command, and yes the odd midge.
"I spent four very happy and formative years studying in St Andrews. The town and the students left me alone to get on with student life, allowing me to hre their freedoms and their pubs.
"I did training as a pilot in Inverness - as well as enjoying the camaraderie of my colleagues it was a privilege to see the majestic sights of Scotland from the air.
"Scotland is a source of some of my happiest memories but also my saddest.
"I was in Balmoral when I was told my mother had died. Still in shock, I found sanctuary in the service at Crathie Kirk that very morning. And in the dark days of grief that followed I found comfort and solace in the Scottish outdoors.
"As a result the connection I feel to Scotland will forever run deep."
But he said alongside the painful memory was one of great joy. "It was here in Scotland 20 years ago this year that I first met Catherine. Needless to say the town where you meet your future wife holds a very special place in your heart."
In his role as Lord High Commissioner Prince William will carry out a range of visits across the country next week. Catherine is due to join him and St Andrews is among the places on their schedule.