I am having trouble understanding the use of に in this following sentence, and also if putting を instead of に would change the meaning of the sentence.
何に興味がありますか。
You cannot use を because there is no transitive verb in this sentence. The only verb in this sentence is あります ("to exist"), which never takes an object.
Let's start with an easier example. What does the following sentence mean?
興味があります。
The literal translation of this is "An interest exists", not "I am interested". 興味 is a noun meaning "interest", が is a subject marker, and あります is a verb meaning "to exist".
Next, you can specify the type of your interest using に. The particle に has many roles, but in this case, you can think に corresponds to "in":
日本語に興味があります。
(lit.) An interest exists in Japanese.
I am interested in Japanese.
You can turn this sentence into a question by replacing 日本語 to 何 and adding か at the end:
何に興味がありますか。
(lit.) In what does an interest exist?
What are you interested in?
Note again that there is no transitive verb. That's why you cannot use を.