You're using the variables correctly.
Consider using Windows Scripting Host. You get a proper scripting language (Visual Basic Script), and can even automate the Excel application from within the script. Some of the problems I mention just don't occur, though there are always ways to shoot yourself in the foot.
Anyhow, if you're set on using batch files, then cmd /? has a lot of helpful information.
Here are some tricks for debugging batch files:
Put "echo" or "rem" in front of commands. Then you can see what it's going to try to do without blowing up your hard drive. I did this with your code:
Code:
C:\test>test.cmd
C:\test>set TxtFile = TextFilename.txt
C:\test>set ExcelFile = ExcelFilename.xls
C:\test>set CMDFile = BatchFile.cmd
C:\test>IF EXIST "C:\test\Folder\" (echo del "C:\test\Folder\" )
C:\test>echo call
call
You're using the del command. Before you delete anything, you
have to validate that it's what you intended to delete. People have lost their jobs over this, so it's a very real danger.
The ways it can go wrong are:
1. Variable substitution fails
Code:
set baz = myDirectory
del /s /q "\%bar%\foo"
I think Windows would just complain about this, but you don't want to rely on it.
2. cd fails
Code:
cd d:\somedir
del /s /q *.*
Two ways this could go wrong:
a. cd fails and you're still in d:\anotherDirectory.
b. cd succeeds, but you're still in c:\ because you forgot to do "c:" by itself.
Since you're using the %CD% environment variable, you're susceptible to this problem. Try to check that some file (like the script itself) is present before you assume you're in the right directory.
3. failure to quote
I noticed that you properly quoted your stuff, so you've got the right idea.
Again, any language can accidentally wipe a hard drive, but batch languages that use variable substitution have these huge vulnerabilities that other languages don't have. (And they're designed for this sort of thing... go figure.)