• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 26
  • Last Modified:

Excel VBA: Define File Path

When writing VBA code I noticed some machines error when I include the file extension. Does anyone know the reason and way to account for this in my code? See examples below:

Example1: Name "C:\TestFolder\TestFile.txt" AS "C:\TestFolder\RenamedFile.txt" <---.txt included: works on some machines and fails on others...
Example2: Name "C:\TestFolder\TestFile" AS "C:\TestFolder\RenamedFile.txt" <--------.txt excluded: works on some machines, but fails on others...

Note: This isn't just when using Name function. I am having this issue for everything VBA that requires defining a file path.
  • 2
1 Solution
NorieVBA ExpertCommented:
How is the code failing?

As far as I know this problem occurs because of Windows settings, specifically whether or not to show file extensions for known file types.

Normally the solution is to always include the file extension, but it really depends on the code being used.
ouestqueAuthor Commented:
Thank you Norie! I agree. I always try to include the file extension. Nonetheless, when I do, VBA throws an error on some machines. I think it is a 1004 error. Let's assume the only code being used is the code below. What would you do if you were in my scenario knowing that it would get a 1004 error on some machines.

Function RenameFile ()
Dim OldFileName, NewFile Name as string

   OldFileName = "C:\TestFolder\TestFile.txt"
   NewFileName = "C:\TestFolder\RenamedFile.txt"
   Name OldFileName AS NewFileName

End Function
NorieVBA ExpertCommented:
I might try something with Dir, or perhaps use the FSO, see below, to rename the file, really depends on the error message.
Dim fso As Object
Dim OldFileName As String
Dim NewFileName As String

   OldFileName = "C:\TestFolder\TestFile.txt"
   NewFileName = "C:\TestFolder\RenamedFile.txt"

   Set fso = CreateObject("Scripting.FileSystemObject")

   fso.MoveFile OldFileName, NewFileName

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now